我有一个小代码可以定期跟踪 CPU 使用情况。不知何故,当我尝试创建文件(“wb”或“w”模式)时,文件已创建但为空。知道为什么会这样吗?
W/O 文件处理程序:
import subprocess
import os
MESSAGE = "mpstat -P ALL | awk '{print $4}'"
SLEEP = "sleep 1"
cmds = [MESSAGE, SLEEP]
def runCommands(commands = cmds):
count =0
while True:
for cmd in cmds:
count+=1
subprocess.call(cmd, shell = True)
runCommands()
使用文件处理程序:
import subprocess
import os
MESSAGE = "mpstat -P ALL | awk '{print $4}'"
SLEEP = "sleep 1"
cmds = [MESSAGE, SLEEP]
def runCommands(commands = cmds):
count =0
while True:
for cmd in cmds:
count+=1
with open('cpu_usage.txt', 'w')as f:
subprocess.call(cmd, stdout = f, shell = True)
runCommands()
mpstat 给出标准输出(不是标准错误)。目标是使用 python 每秒收集 cpu 和内存使用情况,并将其嵌入到应用程序中以收集数据并以图形方式输出。我知道 psutil 在这方面是一个很好的框架,但如果你没有经常使用它。它也可以解决我的问题,因为最后我有一个包含每秒内存和 cpu 使用的图形输出。
最终我正在寻找以下形式的输出:
%CPU %MEM
.. ..
.. ..
.. ..
最后,time vs CPU 和 time vs memory 就可以满足需求。通过获取 cpu 值,我只是解决这个问题的第一步。 ps aux
似乎不是执行我需要的命令的好命令,尽管它提供的输出与我想要的类似。任何想法/想法/建议。
最佳答案
当您使用“w”参数打开一个文件时,它每次都会创建,这意味着当您的while
循环完成时(它不会在您的示例中,但让我们假设它确实如此)- 对文件执行的最后一件事是 sleep 1
命令,它不打印任何内容。使用“a”(追加)标志打开文件,您将在其中获得所有 mpstat
输出。
参见 http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files供完整引用。
但总的来说,尝试在 Python 中做更多的处理并减少对操作系统命令的依赖,如下所示(尽管我仍然根本不会做 AWK 的事情,但无论如何)。
import subprocess
import os
import time
CPU = "mpstat -P ALL | awk 'NR==4 { print $3 }'"
MEM = "free -m | awk 'NR==3 { print $4 }'"
def runCommands():
count = 0
f = open('cpu_usage.txt', 'a')
while True:
t = str(int(time.time()))
cpu = subprocess.check_output(CPU, shell = True).strip()
mem = subprocess.check_output(MEM, shell = True).strip()
f.write(' '.join([t, cpu, mem]))
f.write('\n')
f.flush()
time.sleep(1)
runCommands()
关于python - 写入文件,子进程。调用输出不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16885789/