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.