Python Only Allow Single Instance to Run (or Kill Previous Instance)
December 13, 2020Install pip install psutil
Store pid and command line of current running instance.
NOTE: This will not work in Windows due to fcntl
. Refer to tendo.
import fcntl
import psutil
lockfile_fp = None
def check_instance_running(lockfile):
global lockfile_fp
lockfile_fp = open(lockfile, 'a')
try:
fcntl.lockf(lockfile_fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
lockfile_fp.seek(0)
lockfile_fp.truncate()
# lockfile_fp.write(str(os.getpid()))
lockfile_fp.write(json.dumps({
'pid': os.getpid(),
'cmdline': psutil.Process(os.getpid()).cmdline()
}))
lockfile_fp.flush()
running = False
except IOError:
with open(lockfile, 'r') as fp:
# running = fp.read()
running = json.loads(fp.read())
# running = True
return running
Only allow single instance to run
lockfile = 'test.lock'
data = check_instance_running(lockfile)
if data:
raise Exception(f"Already running: {data['pid']}")
print('START')
while True:
print('.', end='', flush=True)
time.sleep(5)
Kill previous instance
lockfile = 'test.lock'
data = check_instance_running(lockfile)
if data:
p = psutil.Process(data['pid'])
# check cmdline, as pid could be recyled
cmdline = p.cmdline()
# check script and arguments must be the same
# if (p.cmdline() == data['cmdline']):
# check if same script file only: cmdline[0]==python, cmdline[1]==scriptname, cmdline[2..]==arguments
if len(cmdline) >= 2 and len(data['cmdline']) >= 2 and cmdline[1] == data['cmdline'][1]:
print(f"Kill Previous Process: {data['pid']}")
p.terminate()
p.wait()
# create new lock file
util.check_instance_running(lockfile)
print('START')
while True:
print('.', end='', flush=True)
time.sleep(5)
❤️ Is this article helpful?
Buy me a coffee☕ or support my work to keep this space 🖖 and ad-free.
If you can't, do send some 💖 to @d_luaz or help to share this article.
If you can't, do send some 💖 to @d_luaz or help to share this article.
👶 Apps I built
Pixtory App (Alpha) - easily organize photos on your phone into a blog.COVID-19 - data, chart, information & news.
暖心芽 (WIP) 🌞❤️🌱 - reminder of hope, warmth, thoughts and feelings.
Travelopy - travel discovery and journal
LuaPass - offline password manager
WhatIDoNow - a public log of things I am working on now
By Desmond Lua
- algolia
- analytics
- android
- android-ktx
- android-permission
- android-studio
- apps-script
- bash
- bootstrap
- bootstrapvue
- chartjs
- chrome
- cloud-functions
- coding-interview
- coroutines
- crashlytics
- css
- dagger2
- datastore
- datetime
- docker
- eslint
- firebase
- firebase-auth
- firebase-hosting
- firestore
- firestore-security-rules
- flask
- fontawesome
- fresco
- git
- github
- glide
- google-app-engine
- google-cloud-storage
- google-colab
- google-drive
- google-maps
- google-places
- google-play
- google-sheets
- gradle
- html
- hugo
- inkscape
- java
- java-time
- javascript
- jetson-nano
- kotlin
- layout
- lets-encrypt
- lifecycle
- linux
- logging
- lubuntu
- markdown
- mate
- material-design
- matplotlib
- md5
- mongodb
- moshi
- mplfinance
- mysql
- navigation
- nginx
- nodejs
- npm
- nuxtjs
- nvm
- pandas
- payment
- pip
- pwa
- pyenv
- python
- recylerview
- regex
- room
- rxjava
- scoped-storage
- selenium
- social-media
- ssh
- ssl
- static-site-generator
- static-website-hosting
- sublime-text
- ubuntu
- unit-test
- uwsgi
- viewmodel
- viewpager2
- virtualbox
- vue-chartjs
- vue-cli
- vue-router
- vuejs
- vuelidate
- vuepress
- web-development
- web-hosting
- webpack
- windows
- workmanager
- wsl
- yarn