![](/img/trans.png)
[英]Merge stdout and stderr with Python popen AND detect if stderr is empty
[英]Python Popen empty stdout with top
我尝试通过top和python测量CPU使用率:
#!/usr/bin/python
import subprocess
from subprocess import PIPE, Popen
proc = subprocess.Popen("top -c -b -n 1 | grep /usr/local/bin/wineserver | grep -v grep | awk '{print $9}'", shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderr = proc.communicate()
print len(stdout)
print len(stderr)
输出:
0
0
如果我通过外壳运行cmd,我将得到:
54
似乎管道是问题,但我不确定。
解:
os.system("top -c -b -n 1 | grep /usr/local/bin/wineserver | grep -v grep | awk '{print $9}' > top")
stdout = open("top").read().strip("\n")
交互式运行时, top
会将其显示限制为您的屏幕宽度。 通过stdout=PIPE
通过Popen
运行时, top
在终端中未运行,并恢复为其默认列宽。 可以使用环境变量进行更改。
您可以完全抛弃外壳并使用python处理:
#!/usr/bin/python
import subprocess
from subprocess import PIPE, Popen
import os
myenv = os.environ.copy()
myenv["COLUMNS"] = "512"
proc = subprocess.Popen(["top", "-c", "-b", "-n", "1"], stdout=PIPE, stderr=PIPE, env=myenv)
for line in proc.stdout:
columns = print line.strip().split()
if columns[-1] == '/usr/local/bin/wineserver':
print columns
proc.wait()
或者,您可以通过ps
获取CPU信息,并使用其过滤和输出格式说明符来获取所需的信息。 在下面,我使用过滤器显示“ wineserver”的CPU和命令行。
#!/usr/bin/python
import subprocess
from subprocess import PIPE, Popen
proc = subprocess.Popen(["ps", "-ww", "--no-headers", "-C", "wineserver", "-o", "pcpu args"],
stdout=PIPE, stderr=PIPE, env=myenv)
for line in proc.stdout:
pcpu, command = print line.strip().split(" ", 1)
print pcpu, command
proc.wait()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.