搜索
首页后端开发Python教程如何在Python中检查应用程序是否打开?

如何在Python中检查应用程序是否打开?

Aug 26, 2023 pm 06:49 PM
python应用程序检查

如何在Python中检查应用程序是否打开?

正在执行的程序称为进程。进程可以是当前操作系统上运行的应用程序,也可以是与操作系统相关的应用程序。如果一个应用程序与操作系统相关,它首先会创建一个进程来执行自己。

其他应用程序依赖操作系统服务来执行。大多数应用程序是操作系统服务以及维护操作系统、软件和硬件的后台应用程序。

在 python 中,我们有不同的方法来检查应用程序是否打开。让我们一一详细了解它们。

使用 psutil.process_iter() 函数

psutil 是 python 中的一个模块,它为用户提供一个接口来检索正在运行的进程和系统利用率的信息。可用于Linux、windows、macOs、solaris、AIX等主流操作系统以及API平台。

psutil 模块的 process_iter() 函数帮助我们检索有关正在运行的进程的信息,例如进程名称、进程 ID、CPU 使用情况、内存使用情况等。它还提供有关系统利用率的信息,例如磁盘使用情况、网络使用情况等。

示例

在此示例中,我们试图查明名为“Chrome.exe”的进程当前是否正在我们的系统中运行。

import psutil
def check_if_process_running(process_name):
    for process in psutil.process_iter(['name']):
        if process.info['name'] == process_name:
            return True
    return False
check_if_process_running("Chrome.exe")

输出

False

示例

这是 psutil 模块的 process_iter() 函数的另一个示例,它提供了进程的详细信息。

import psutil
processes = psutil.process_iter()
for process in processes:
    print(f"Process name: {process.name()} | PID: {process.pid}")
cpu_percent = psutil.cpu_percent()
print(f"CPU usage: {cpu_percent}%")
memory_usage = psutil.virtual_memory()
print(f"Total memory: {memory_usage.total / 1024 / 1024:.2f} MB")
print(f"Available memory: {memory_usage.available / 1024 / 1024:.2f} MB")
print(f"Memory usage: {memory_usage.percent}%")

输出

以下是 process_iter() 的输出,它提供了有关应用程序的全部信息。

Process name: chrome.exe | PID: 15964
Process name: chrome.exe | PID: 16876
CPU usage: 10.6%
Total memory: 12152.65 MB
Available memory: 5849.83 MB
Memory usage: 51.9%

使用子流程模块

子进程模块是检查应用程序是否正在运行或停止的另一种方法。使用 subprocess 模块,我们可以从当前的 Python 程序启动一个新的应用程序。我们可以使用 check_output() 方法获取程序、命令的输出。

示例

在下面的示例中,我们尝试使用 check_output() 函数验证应用程序是否打开 –

import subprocess
def is_process_running(process_name):
    cmd = 'tasklist /fi "imagename eq {}"'.format(process_name)
    output = subprocess.check_output(cmd, shell=True).decode()
    if process_name.lower() in output.lower():
        return True
    else:
        return False
is_process_running("chrome.exe")

输出

True

使用wmi模块

Windows Management Instrumentation 是 Windows 操作系统中的一组工具,允许管理员管理远程和本地计算机。

在Python中,我们有wmi模块,它可以帮助我们检查应用程序是否正在运行。以下代码用于在python环境中安装wmi。

pip install wmi

示例

在此示例中,我们将应用程序名称作为输入参数传递给 wmi 模块的 WMI() 函数,以检索具有进程 ID 的应用程序的状态。

import wmi
f = wmi.WMI()
for process in f.Win32_Process():
    print(f"{process.ProcessId:>5} {process.Name}")

输出

下面是wmi模块的WMI()函数的输出。

0 System Idle Process
    4 System
  124 Registry
  524 smss.exe
  752 csrss.exe
  868 csrss.exe
  888 wininit.exe
  940 services.exe
  960 lsass.exe
  320 winlogon.exe
  980 svchost.exe
 1048 fontdrvhost.exe
 1056 fontdrvhost.exe
 1144 WUDFHost.exe
 1180 svchost.exe
 1268 svchost.exe
 1292 WUDFHost.exe
 1396 svchost.exe
 1404 svchost.exe
 1412 svchost.exe
 1528 svchost.exe
 1640 dwm.exe
 1660 svchost.exe

以上是如何在Python中检查应用程序是否打开?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:tutorialspoint。如有侵权,请联系admin@php.cn删除
在Python阵列上可以执行哪些常见操作?在Python阵列上可以执行哪些常见操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些类型的应用程序中,Numpy数组常用?在哪些类型的应用程序中,Numpy数组常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什么时候选择在Python中的列表上使用数组?您什么时候选择在Python中的列表上使用数组?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

您如何在python列表中访问元素?您如何在python列表中访问元素?Apr 26, 2025 am 12:03 AM

toAccesselementsInapythonlist,useIndIndexing,负索引,切片,口头化。1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Python的科学计算中如何使用阵列?Python的科学计算中如何使用阵列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何处理同一系统上的不同Python版本?您如何处理同一系统上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

与标准Python阵列相比,使用Numpy数组的一些优点是什么?与标准Python阵列相比,使用Numpy数组的一些优点是什么?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具