Reputation: 8352
On Windows, using the WMI library, I can get a list of running Python programs like this
c = wmi.WMI()
for process in c.Win32_Process(name="python.exe"):
print(process.ProcessId, process.Name)
An example output is
21084 python.exe
10184 python.exe
12320 python.exe
How can I find out which of these processes is the currently running script?
I'm trying to use process.Terminate() on all the other Python scripts running, because sometimes a Python script started by a GUI doesn't close. But I want to avoid killing the script that does the cleanup - so I need a way of identifing it.
Upvotes: 0
Views: 1952
Reputation: 12672
An easy way is to use os
module to do that:
import os, wmi
c = wmi.WMI()
for process in c.Win32_Process(name="python.exe"):
print(process.ProcessId, process.Name)
print("current processId:", os.getpid())
Also you could use win32api
of pywin32
:
print("current processId:", win32api.GetCurrentProcessId())
I also run another script on my PC, this gave me:
17944 python.exe
10676 python.exe
current processId: 10676
Upvotes: 1