i would like my Python script to check, if it is already running and if yes, kill the old process. i tried this, but it doesn't really work...
import os
import subprocess
import signal
process_name = "python " + os.path.abspath(__file__)
proc = subprocess.Popen(["pgrep", process_name], stdout=subprocess.PIPE)
# Kill process.
for pid in proc.stdout:
os.kill(int(pid), signal.SIGTERM)
# Check if the process that we killed is alive.
try:
os.kill(int(pid), 0)
raise Exception("""wasn't able to kill the process
HINT:use signal.SIGKILL or signal.SIGABORT""")
except OSError as ex:
continue
It doesn't kill the old process and runs multiple times now.
This question is very similar to Check to see if python script is running
I suggest you use the PidFile module, it will handle everything for you.
import pidfile
import time
print('Starting process')
try:
with pidfile.PIDFile():
print('Process started')
time.sleep(30)
except pidfile.AlreadyRunningError:
print('Already running.')
print('Exiting')
Try to run twice this script with two terminals
I am not related to the owner of the library, I just found it
My current solution looks like this (on OSX). I am using pgrep in combination with regexp
import subprocess
cmd = ['pgrep -f .*python.*testing03.py']
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
my_pid, err = process.communicate()
if len(my_pid.splitlines()) >0:
print("Running")
exit()
else:
print("Not Running")
As far as i have tested this should work even if the python string differs. Location of the script doesn't matter either
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With