I'm trying to get and kill all other running python instances of the same script, I found an edge case where the path is not in psutil's cmdline list, when the process is started with ./myscript.py and not python ./myscript.py
the script's content is, note the shebang:
#!/bin/python
import os
import psutil
import sys
import time
for proc in psutil.process_iter():
if "python" in proc.name():
print("name", proc.name())
script_path = sys.argv[0]
proc_script_path = sys.argv[0]
if len(proc.cmdline()) > 1:
proc_script_path = proc.cmdline()[1]
else:
print("there's no path in cmdline")
if script_path.startswith("." + os.sep) or script_path.startswith(".." + os.sep):
script_path = os.path.normpath(os.path.join(os.getcwd(), script_path))
if proc_script_path.startswith("." + os.sep) or proc_script_path.startswith(".." + os.sep):
proc_script_path = os.path.normpath(os.path.join(proc.cwd(), proc_script_path))
print("script_path", script_path)
print("proc_script_path", proc_script_path)
print("my pid", os.getpid())
print("other pid", proc.pid)
if script_path == proc_script_path and os.getpid() != proc.pid:
print("terminating instance ", proc.pid)
proc.kill()
time.sleep(300)
how can I get the script path of a python process when it's not in psutil's cmdline?
解决方案
When invoking a python script like this, the check if 'python' in proc.name() is the problem. This will not show python or python3 for the scripts in question, but it will show the script name. Try the following:
import psutil
for proc in proc.process_iter():
print('Script name: {}, cmdline: {}'.format(proc.name(), proc.cmdline()))
You should see something like ():
Script name: myscript.py, cmdline: ['/usr/bin/python3', './myscript.py']
Hope this helps.