[英]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.