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?

Asked By: GriMel

||

Answers:

Look at psutil.Process(i).cmdline() docs. Your example would return

['python', 'script_name']
Answered By: sberry

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().

Answered By: David Harris

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
Answered By: iam-py-test

Note that cmdline is a function and requires a ()
print(proc.cmdline()[1])

Answered By: Andy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.