使用 Python 在 Windows 上检查进程是否正在运行 [英] Check if a process is running or not on Windows with Python
问题描述
我正在尝试创建一个 Python 脚本,稍后我将其作为服务运行.现在我只想在 iTunes 运行时运行代码的特定部分.我从一些研究中了解到,轮询整个命令列表然后搜索该列表的应用程序的成本很高.
I am trying to create a python script which I will later run as a service. Now I want to run a particular part of the code only when iTunes is running. I understand from some research that polling the entire command list and then searching for the application for that list is expensive.
我发现基于 UNIX 的操作系统上的进程会创建一个锁定文件来通知程序当前正在运行,此时我们可以使用 os.stat(location_of_file)
来检查文件存在以确定程序是否正在运行.
I found out that processes on UNIX-based operating systems create a lock file to notify that a program is currently running, at which point we can use os.stat(location_of_file)
to check if the file exists to determine if a program is running or not.
是否有在 Windows 上创建的类似锁定文件?
Is there a similar lock file created on Windows?
如果不是,Python 中有哪些方法可以确定进程是否正在运行?
If not what are the various ways in Python by which we can determine if a process is running or not?
我使用的是 python 2.7 和 iTunes COM 接口.
I am using python 2.7 and iTunes COM interface.
推荐答案
您不能依赖 Linux 或 Windows 中的锁定文件.我会咬紧牙关,遍历所有正在运行的程序.我真的不相信它会像你想象的那样昂贵".psutil 是一个优秀的跨平台 python 模块电缆,用于枚举系统上所有正在运行的程序.
You can not rely on lock files in Linux or Windows. I would just bite the bullet and iterate through all the running programs. I really do not believe it will be as "expensive" as you think. psutil is an excellent cross-platform python module cable of enumerating all the running programs on a system.
import psutil
"someProgram" in (p.name() for p in psutil.process_iter())
这篇关于使用 Python 在 Windows 上检查进程是否正在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!