我在一个项目中工作,该项目需要获取每个过程的PID列表:
我正在为此项目使用Python,并且我需要它在Windows和** ix上均可工作。
我已经对SO(List running processes on 64-bit Windows)进行了一些研究,但是该解决方案特定于Windows OS。我不知道下一步要去哪里或要使用哪个模块。
感谢adv。
答案 0 :(得分:0)
如前所述,psutil
似乎是满足您需求的最佳工具:
https://github.com/giampaolo/psutil#process-management
以下是如何检索数据的示例:
from datetime import datetime
import psutil
# Getting the list of all processes (as a list, or with other attributes)
list_pids = psutil.pids()
for proc in psutil.process_iter(attrs=['pid', 'name', 'memory_percent']):
print(proc.info)
print("===SINGLE PROCESS==")
try:
notepad = subprocess.Popen("notepad.exe")
pid = notepad.pid
sleep(0.5)
# We get a "Process" from the PID
process = psutil.Process(pid)
# We can then retrieve different information on the processs
print(f"NAME: {process.name()}")
print(f"ID: {process.pid}")
print(f"STATUS: {process.status()}")
print(f"STARTED: {datetime.fromtimestamp(process.create_time())}")
print(f"CPU: {process.cpu_percent(interval=1.0)}%")
print(f"MEMORY %: {process.memory_percent():.1f}%")
finally:
notepad.kill()