我有一個小的代碼,它會定期跟蹤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在這方面是一個很好的框架,但是如果你沒有玩過它的話。它也可以解決我的問題,因爲最終我有一個圖形輸出,其中包含每秒使用mem和cpu的情況。
最後,我要尋找的輸出是下面的形式:
%CPU %MEM
.. ..
.. ..
.. ..
,並在最後一個時間與CPU時間和內存VS將足夠的需求。我只是通過獲取CPU值來解決這個問題。 ps aux
似乎不是一個很好的命令來做我需要的東西,雖然它給出了與我想要的相似的輸出。任何想法/想法/建議。
解決您的縮進:P –
爲什麼不ü用subprocess.popen()從u能的std出和std犯錯太 – Rajeev
我不需要標準錯誤的mpstat的是給了我標準輸出。 –