Reputation: 55
In my Python script, i want to check if otherscript.py
is currently being run on the (Linux) system. The psutil library looked like a good solution:
import psutil
proc_iter = psutil.process_iter(attrs=["name"])
other_script_running = any("otherscript.py" in p.info["name"] for p in proc_iter)
The problem is that p.info["name"]
only gives the name of the executable of a process, not the full command. So if python otherscript.py
is executed on the system, p.info["name"]
will just be python
for that process, and my script can't detect whether or not otherscript.py
is the script being run.
Is there a simple way to make this check using psutil or some other library? I realize i could run the ps
command as a subprocess and look for the otherscript.py
in the output, but i'd prefer a more elegant solution if one exists.
Upvotes: 3
Views: 6064
Reputation: 61
this code is checking the process ongoing. it doesn't matter Linux or Window
import psutil
proc_iter = psutil.process_iter()
for i in proc_iter:
print(i)
Upvotes: 0
Reputation: 13066
http://psutil.readthedocs.io/en/latest/#find-process-by-name Take a look at the second example which inspects name(), cmdline() and exe().
For reference:
import os
import psutil
def find_procs_by_name(name):
"Return a list of processes matching 'name'."
ls = []
for p in psutil.process_iter(attrs=["name", "exe", "cmdline"]):
if name == p.info['name'] or \
p.info['exe'] and os.path.basename(p.info['exe']) == name or \
p.info['cmdline'] and p.info['cmdline'][0] == name:
ls.append(p)
return ls
Upvotes: 2
Reputation: 578
I wonder if this works
import psutil
proc_iter = psutil.process_iter(attrs=["pid", "name", "cmdline"])
other_script_running = any("otherscript.py" in p.info["cmdline"] for p in proc_iter)
Upvotes: 6