[英]How to check in Mac OSX with Python if a process is RUNNING or not
嘗試這個。 如果它返回一個進程 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.