如何检查应用程序是否在Python打开?
这篇文章是关于如何使用Python检查应用程序是否在系统中打开的。您还可以参考文章Python – 获取正在运行的进程列表以获取更多信息。
在下面的方法中,我们将检查chrome.exe是否在我们的系统中打开。
使用 psutil
psutil是Python的系统监控和系统利用模块。它主要用于系统监控、分析和限制进程资源以及管理正在运行的进程。可以监控 CPU、内存、磁盘、网络、传感器等资源的使用情况。它在Python 2.6、2.7 和 3.4+ 版本中受支持。您可以使用以下命令安装psutil模块
pip install psutil
我们将使用psutil.process_iter()方法,它返回一个迭代器,为本地机器上的所有正在运行的进程产生一个进程类实例。
Python3
# import module
import psutil
# check if chrome is open
"chrome.exe" in (i.name() for i in psutil.process_iter())
Python3
# Import module
import wmi
# Initializing the wmi constructor
f = wmi.WMI()
flag = 0
# Iterating through all the running processes
for process in f.Win32_Process():
if "chrome.exe" == process.Name:
print("Application is Running")
flag = 1
break
if flag == 0:
print("Application is not Running")
输出:
True
我们导入psutil模块。然后我们使用psutil.process_iter()在本地机器上所有正在运行的进程中搜索chrome.exe 。如果找到,它将返回输出为TRUE ,否则为FALSE 。
使用 WMI(仅限 Windows 用户)
wmi模块可用于获取 Windows 机器的系统信息,可以使用以下命令进行安装:
pip install wmi
它的工作方式类似于psutil 。在这里,我们检查正在运行的进程列表中是否存在特定的进程名称。
蟒蛇3
# Import module
import wmi
# Initializing the wmi constructor
f = wmi.WMI()
flag = 0
# Iterating through all the running processes
for process in f.Win32_Process():
if "chrome.exe" == process.Name:
print("Application is Running")
flag = 1
break
if flag == 0:
print("Application is not Running")
输出:
Application is Running
我们导入wmi模块。然后我们通过遍历进程名称在本地机器上所有正在运行的进程中搜索chrome.exe 。如果它与过程匹配。名称,它将打印Application is Running ,否则Application is not Running 。