繁体   English   中英

如果进程正在运行,如何使用 Python 签入 Mac OSX

[英]How to check in Mac OSX with Python if a process is RUNNING or not

我在 mac osx 10.9 上使用 python 2.7。

我想检查一个进程是否正在运行。 我调查了这个问答,但结果并不理想。

我想检查是否有任何特定名称的进程正在运行

尝试这个。 如果它返回一个进程 id,那么你有这个进程正在运行。 使用您的进程名称而不是firefox

# Python2
import commands
commands.getoutput('pgrep firefox')

由于命令模块不再在 python 3x 中,我们可以在这里使用subprocess进程模块接收进程 ID。

# Python3
import subprocess
process = subprocess.Popen('pgrep firefox', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
my_pid, err = process.communicate()

这里my_pid将是进程id

使用模块psutil 例如:

import psutil

# ...    

if pid in psutil.get_pid_list():
    print(pid, "is running")

编辑:您可以像这样获取所有正在运行的进程的 pid 和名称:

for p in psutil.process_iter():
    if p.name == 'firefox':
        print("firefox is running")
        break

我只是在尝试上面的代码,但它对我使用 python 2.7 不起作用还没有在 python 3 上尝试过代码。发布更新的代码,它可能会对某人有所帮助

for p in psutil.process_iter():  # iterate through all running processes 
    if p.name() == 'firefox':
        print("firefox is running")
        break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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