Python detect a python script's name in the list of processes
Question:
I know I can use psutil
to get a list of running processes’ names like this
import psutil
for i in psutil.pids():
print(psutil.Process(i).name())
However, If i run a python script with python, psutil only will show me that I have an instance of python running.
So, my question is – if I run a python script:
python script_name
is it possible to detect script_name
by psutil?
Answers:
Look at psutil.Process(i).cmdline()
docs. Your example would return
['python', 'script_name']
The psutil documentation states that the cmdline() method returns the command line of the process. If the command line is python script_name
, the second word will be the actual script name. To get this information I’d change psutil.Process(i).name()
to psutil.Process(i).cmdline()
.
You will need to read the script name from the command line arguments:
import psutil
for proc in psutil.process_iter():
try:
if "python" in proc.name():
print(proc.cmdline[1])
except:
pass
Note that cmdline is a function and requires a ()
print(proc.cmdline()[1])
I know I can use psutil
to get a list of running processes’ names like this
import psutil
for i in psutil.pids():
print(psutil.Process(i).name())
However, If i run a python script with python, psutil only will show me that I have an instance of python running.
So, my question is – if I run a python script:
python script_name
is it possible to detect script_name
by psutil?
Look at psutil.Process(i).cmdline()
docs. Your example would return
['python', 'script_name']
The psutil documentation states that the cmdline() method returns the command line of the process. If the command line is python script_name
, the second word will be the actual script name. To get this information I’d change psutil.Process(i).name()
to psutil.Process(i).cmdline()
.
You will need to read the script name from the command line arguments:
import psutil
for proc in psutil.process_iter():
try:
if "python" in proc.name():
print(proc.cmdline[1])
except:
pass
Note that cmdline is a function and requires a ()
print(proc.cmdline()[1])