[英]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在 Windows 上,使用WMI库,我可以获得运行 Python 程序的列表,例如
c = wmi.WMI()
for process in c.Win32_Process(name="python.exe"):
print(process.ProcessId, process.Name)
An example output is一个示例 output 是
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.我正在尝试在所有其他正在运行的 Python 脚本上使用 process.Terminate(),因为有时由 GUI 启动的 Python 脚本不会关闭。 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:一个简单的方法是使用os
模块来做到这一点:
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
:你也可以使用pywin32
的win32api
:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.