3 回答

TA貢獻1880條經驗 獲得超4個贊
您需要將命令的輸出發送到/dev/null
>/usr/bin/time -f "\t%E real,\t%U user,\t%S sys" ls -Fs >/dev/null
0:00.01 real, 0.00 user, 0.01 sys
這里的復雜性是我們想要丟棄命令輸出但存儲命令的輸出/usr/bin/time。
將 的輸出存儲usr/bin/time為變量稍微復雜一些,因為/usr/bin/time它在 stderr 上顯示它的輸出。所以我們需要將命令輸出發送到dev/null,然后將 time 的輸出從 stderr 重定向并捕獲到一個變量中。假設您可能想要執行比 ls -R 更復雜的命令,我們通常會調用 sh -c 'exec ' 這將在未來為您提供更多選擇。因此:
result=$(/usr/bin/time -f "\t%E MM:ss:mm" sh -c 'exec ls -R >/dev/null' 2>&1 tee)
執行輸出:
>result=$(/usr/bin/time -f "\t%E MM:ss:mm" sh -c 'exec ls -R >/dev/null' 2>&1 tee
); echo $result
0:20.60 MM:ss:mm
在這里我們將結果捕獲為環境變量
>echo $result
0:20.60 MM:ss:mm
最后我們到達:
os.popen("/usr/bin/time -f '%E MM:ss:mm' sh -c 'exec ls -R >/dev/null' 2>&1 tee").read()
執行輸出:
>python3
Python 3.6.9 (default, Apr 18 2020, 01:56:04)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.popen("/usr/bin/time -f '%E MM:ss:mm' sh -c 'exec ls -R >/dev/null' 2>&1 tee").read()
'0:19.89 MM:ss:mm\n'
希望以上內容為您指明了正確的方向。

TA貢獻1813條經驗 獲得超2個贊
它適用于subprocess但注意/usr/bin/time使用 stderr
import subprocess
proc = subprocess.Popen(["/usr/bin/time -f \"\t%E M:ss:mm, \t%P CPU\" ls -R"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print("program output:", err.decode("utf-8"))
輸出:
program output: 0:00.00 M:ss:mm, 100% CPU

TA貢獻2012條經驗 獲得超12個贊
這段代碼在 python 2.7 上對我有用
import os
from datetime import datetime
CPU_Pct="Cpu Usage :"+str(round(float(os.popen('''grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }' ''').readline()),2))+ " time:" + datetim$
print(CPU_Pct)
輸出會像
5.74 time:2020-07-07 10:53:22
如果你也想獲得內存的使用,你可以將這一行添加到你的代碼中
tot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])
最終代碼可能是這樣的:
import os
from datetime import datetime
CPU="|| CPU Usage :"+str(round(float(os.popen('''grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }' ''').readline()),2))
Time = "|| time:" + datetime.now().strftime('%H:%M:%S')
tot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])
Memory ="|| memory :"+ str(used_m) +"/"+str(tot_m)
print(Time + CPU+Memory)
這是輸出:
|| time:11:02:33|| CPU Usage :5.74|| memory :13847/37529
- 3 回答
- 0 關注
- 195 瀏覽
添加回答
舉報