子流程上的跨平台资源使用情况

问题描述:

首先,如果在对不起重复之前已问过此问题,但我在任何地方都找不到我的问题的答案.

因此,我刚接触Python,目前正在为Web应用程序开发包装程序. 该包装器使用Popen启动一个子流程,然后将有关该子流程的信息发送到Web应用程序.到目前为止,一切都很好.

So, I am pretty new to Python, and I am currently working on a wrapper for a web application. This wrapper starts a subprocess using Popen and then sends information about that subprocess to the web application. Everything is working great so far.

现在我唯一的问题是; 能否获得子进程( RAM和CPU )的资源使用情况?
如果是这样,我将如何去做?跨平台的功能很棒,但是适用于Windows,Mac和Linux的另一种方法也可以.

Now the only question I have is; Is it possible to get resource usage of a subprocess (RAM and CPU)?
If so, how would I go about doing that? Something cross-platform would be awesome, but a different method for Windows, Mac and Linux would work as well.

如果无法通过子流程获取.我如何从另一个进程获取资源使用情况?

If it isn't possible to get via subprocess. How would I got about fetching resource usage from another process?

任何帮助将不胜感激!
感谢您的时间!

Any help would be appreciated!
Thanks for your time!

psutil 提供了一个跨平台的解决方案来获取子流程的资源使用情况,例如:

psutil provides a cross-platform solution to get resource usage of a subprocess e.g.:

import random
import psutil # $ pip install psutil

p = psutil.Process(random.choice(psutil.pids()))
print(p.name())
print(p.cpu_times())
print(p.memory_info())

要获取现有subprocess.Popen实例的信息,只需将popen_instance.pid传递给psutil.Process.您也可以直接使用 psutil.Popen 创建子流程.

to get the info for an existing subprocess.Popen instance just pass popen_instance.pid to psutil.Process. You could also create a subprocess using psutil.Popen directly.