I have a Python script that starts up when Pi boots. However, it may be restarted remotely, or I may want to kill it before re-launching it from Visual Studio for debugging/further development. Therefore, when this script launches, it needs to check if there are other instances of it, and kill them, without killing itself. So, at the beginning of the script, I have this code:
import os
import subprocess
def killOtherScriptInstances():
myPID = os.getpid()
pids = list(map(int, subprocess.check_output('pgrep -f test.py', shell=True).decode('UTF-8').splitlines()))
for pid in pids:
if pid != myPID:
subprocess.check_output('kill -9 ' + str(pid), shell=True)
killOtherScriptInstances()
If my script is started from shell, this function works just fine. However, if the script is launched from Visual Studio Code with RemoteSSH, for whatever reason pgrep -f test.py
reports two PIDs for the current script instance (even if there were no instances running prior). It kills one that does not match the PID reported by os.getpid()
, but that still terminates the current instance of the script.
Can someone explain why running my script from shell (python3 test.py
) produces one instance and one PID for this script, but running the same script from Visual Studio Code produces two? How do I work around this issue?