pythonpsutil

Check which Python process is running 'myscript.py' on Windows, Linux


Finding out that Python is running is rather easy. But how can I find out which Python process is the one running myscript.py?

I took help from this Check if a process is running or not on Windows? eventually using psutil as simple as:

import psutil
for proc in psutil.process_iter(['pid', 'name']):
    if "python"  in str(proc.info).lower(): 
       print(proc.info)

This results e.g. in this output:

{'pid': 34461, 'name': 'python'}
{'pid': 1245157, 'name': 'python'}
{'pid': 1433410, 'name': 'python'}
{'pid': 2176252, 'name': 'python3.11'}
{'pid': 2894859, 'name': 'python'}
{'pid': 2973672, 'name': 'python'}
{'pid': 3354315, 'name': 'python'}

Very easy so far, but which of these Python processes is the one which runs myscript.py?

A solution must be possible from within Python and must run on Windows, and Linux. Hopefully, also be on Mac.


Solution

  • Here is a solution working on MacOs, Linux and Windows:

    import psutil
    for proc in psutil.process_iter(['pid', 'name']):
        if "python"  in str(proc.info).lower(): 
           print(proc.cmdline())
    

    It gives a useful output that you can use to find the good process :

    ['/opt/homebrew/Cellar/python@3.8/3.8.16/Frameworks/Python.framework/Versions/3.8/Resources/Python.app/Contents/MacOS/Python', '/Users/XXX/Code/test.py']