0

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.

Ajeet Verma
  • 2,938
  • 3
  • 13
  • 24
ullix
  • 333
  • 1
  • 3
  • 14

1 Answers1

0

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']
L.GAYET
  • 86
  • 6
  • Duuuh, so obvious, how could I have possibly missed it? Many thanks. Can now add that it not only works on Mac, as you said, but also on Win10, and Linux! – ullix May 11 '23 at 15:48
  • Ahah it happens, i add it to the answer :) – L.GAYET May 11 '23 at 16:13