2

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?

4 Answers 4

7

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

['python', 'script_name']
Sign up to request clarification or add additional context in comments.

1 Comment

The latest psutil docs are here, as the above link is long outdated.
2

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

Comments

1

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

Comments

0

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

1 Comment

What? There is no cmdline in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.