[英]Python Popen empty stdout with top
I try to measure CPU usage via top and python: 我尝试通过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)
Output: 输出:
0 0
0 0
If I run the cmd via shell I get: 如果我通过外壳运行cmd,我将得到:
54 54
It seems the piping is the issue but I am not sure. 似乎管道是问题,但我不确定。
Solution: 解:
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")
When run interactively, top
limits its display to your screen width. 交互式运行时,
top
会将其显示限制为您的屏幕宽度。 When run through Popen
with stdout=PIPE
, top
is not running in a terminal and reverts to its default column width. 通过
stdout=PIPE
通过Popen
运行时, top
在终端中未运行,并恢复为其默认列宽。 This can be changed with an environment variable. 可以使用环境变量进行更改。
You could ditch the shell completely and process with python: 您可以完全抛弃外壳并使用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()
Alternately, you can get CPU information through ps
and use its filtering and output format specifiers to just grab the information you want. 或者,您可以通过
ps
获取CPU信息,并使用其过滤和输出格式说明符来获取所需的信息。 Below I use filters to display CPU and command line for "wineserver" only. 在下面,我使用过滤器显示“ 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.