简体   繁体   中英

In Python on Windows, how can I identify the current process ID using WMI or pywin32?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM