3

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.

3 Answers 3

7

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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)

Comments

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.