I'm executing an external program through Python. I want to know what is the best choice for calling the outside program, with subprocess.Popen()
or with subprocess.call()
. Also, I need to measure elapsed time, the amount of memory and CPU used by the external program. I've heard of psutil
, but I don't really know which to choose.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- How to get the return code of a shell script in lu
- Evil ctypes hack in python
(I'm going to assume you only need the information available in your platform's
rusage
. And, since Windows has no such thing at all, I'm also going to assume you don't care about Windows. If you need additional information that's only available in some platform-specific way (reading out of Linux'sproc
filesystem, or calling AIX's monitor APIs, or whatever), you pretty much can't do this with the stdlib, and thepsutil
answer is the only one.)The
subprocess
library wraps up callingfork
, then anexecv
-family function in the child and awaitpid
-family function in the parent. (You can see this by starting with the source tocall
and tracing down into the other calls from there.)Unfortunately, the easy way to get resource usage from a child is to call
wait3
orwait4
, notwait
orwaitpid
. Sosubprocess
gets you maddeningly close to what you want, but not quite there.But you've got a few options:
getrusage(RUSAGE_CHILDREN)
is all you need.psutil
(or platform-specific code) to get resource information fromproc.pid
before reaping the child.psutil
to do everything, leavingsubprocess
behind.subprocess.Popen
to override itswait
method.The last one is a lot simpler than it sounds. If you look at the source, there are only 3 places where
os.waitpid
is actually called, and only one of them will be the one that affects your code; I think it's the one in_try_wait
. So (untested):And now:
Compare that to using a hybrid with
psutil
(which won't even work when used this way on many platforms…):Of course the latter isn't more complex for not good reason, it's more complex because it's a whole lot more powerful and flexible; you can also get all kinds of data that
rusage
doesn't include, and you can get information every second while the process is running instead of waiting until it's done, and you can use it on Windows, and so on…