![](/img/trans.png)
[英]How would I store the shell command output to a variable in python?
[英]Python: Store command output in variable
我想使用/usr/bin/time
工具測量命令的時間和 CPU 使用率。 但是,當我執行os.popen( "/usr/bin/time -f \t%E MM:ss:mm ls -R" ).read()
時,它還會存儲ls -R
的 output 。 我該怎么做才能只存儲/usr/bin/time
output?
我也用subprocess
嘗試過,但它也不起作用。
out = subprocess.Popen(['/usr/bin/time', '-f', '"\t%E MM:ss:mm"', 'ls', '-R'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout,stderr = out.communicate()
print( stdout )
在終端中運行命令如下所示:
輸入:
/usr/bin/time -f "\t%E M:ss:mm, \t%P CPU" ls -R
Output:
.:
Dockerfile input output README.md src Test.py
./input:
links.txt raw yuv
./input/raw:
./input/yuv:
./output:
./src:
InstallEncoderArm.sh InstallEncoderx86.sh RunTests.py
0:00.00 M:ss:mm, 100% CPU
需要將命令的output發送到/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
這里的復雜性是我們想要丟棄命令 output 但存儲/usr/bin/time
命令的 output。
將usr/bin/time
的 output 存儲為變量有點復雜,因為/usr/bin/time
在 stderr 上顯示其 output。 所以我們需要將命令 output 發送到dev/null
,然后從 stderr 重定向時間的 output 並將其捕獲到變量中。 假設您可能想要執行比 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)
執行 Output:
>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'
希望以上內容為您指明正確的方向。
此代碼在 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)
output 會像
5.74 time:2020-07-07 10:53:22
如果您也想使用 memory ,您可以將此行添加到您的代碼中
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)
這是 output:
|| time:11:02:33|| CPU Usage :5.74|| memory :13847/37529
它適用於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"))
Output:
program output: 0:00.00 M:ss:mm, 100% CPU
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.