【问题标题】:How to get the list of pids and information on PID by using Python (OS independent)?如何使用 Python(独立于操作系统)获取 pid 列表和有关 PID 的信息?
【发布时间】:2019-01-31 14:37:46
【问题描述】:

我正在一个项目中工作,该项目需要为每个进程获取一个 PID 列表:

  • 进程名称
  • 进程开始时间
  • 内存和 CPU 使用率

我在这个项目中使用 Python,我需要它同时在 Windows 和 **ix 上工作。

我对 SO (List running processes on 64-bit Windows) 进行了一些研究,但该解决方案特定于 Windows 操作系统。我不知道下一步该去哪里或使用哪个模块。

感谢您的建议。

【问题讨论】:

  • @jonrsharpe,通过这个链接(stackoverflow.com/questions/1632234/…)我有 Pids 和进程名称,但它是特定于 win 操作系统的。所以,现在我没有得到这些问题的答案 - 1.如何使所有操作系统都通用? 2.如何获取启动时间、内存和cpu使用率?谢谢
  • 这很广泛,我建议你做更多的研究。
  • @jonrsharpe,您能否建议我任何可以轻松获得解决方案的特定模块。
  • 对外部资源(如模块、库等)的建议在此处明确无关 - 请参阅help center
  • @jonrsharpe,我真的很抱歉。你来这里是为了让某人失去动力吗?

标签: linux python-3.x windows unix


【解决方案1】:

如前所述,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()

【讨论】:

  • 感谢您的精彩解释。它满足我的要求。
  • @ManojKnitan 如果您喜欢这个答案,您可以 +1。干杯
  • Jean-Francois:您知道如何在任何特定时间(假设是凌晨 4:00)拍摄内存使用情况的快照吗?感谢您的建议。
  • @ManojKnitan 特定命令的内存使用情况还是系统使用的所有内存?
  • Jean:系统使用的所有内存,但应该在特定时间。
猜你喜欢
  • 2014-11-21
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
相关资源
最近更新 更多