[英]Python: Store command output in variable
I'd like to measure the time and cpu usage of a command with the /usr/bin/time
tool.我想使用/usr/bin/time
工具测量命令的时间和 CPU 使用率。 But when I do os.popen( "/usr/bin/time -f \t%E MM:ss:mm ls -R" ).read()
it also stores the output of ls -R
.但是,当我执行os.popen( "/usr/bin/time -f \t%E MM:ss:mm ls -R" ).read()
时,它还会存储ls -R
的 output 。 What can I do to only store the /usr/bin/time
output?我该怎么做才能只存储/usr/bin/time
output?
I also tried it with subprocess
but it doesn't work either.我也用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 )
Running the command in the terminal looks like this:在终端中运行命令如下所示:
Input:输入:
/usr/bin/time -f "\t%E M:ss:mm, \t%P CPU" ls -R
Output: 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
You need to send the output of the command to /dev/null
需要将命令的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
The complexity here is we want to throw away the command output but store the output of the /usr/bin/time
command.这里的复杂性是我们想要丢弃命令 output 但存储/usr/bin/time
命令的 output。
To store the output of usr/bin/time
as a variable is a little more complicated as /usr/bin/time
presents its output on stderr.将usr/bin/time
的 output 存储为变量有点复杂,因为/usr/bin/time
在 stderr 上显示其 output。 So we need to send the command output to dev/null
, then redirect the output of time from stderr and capture it in a variable.所以我们需要将命令 output 发送到dev/null
,然后从 stderr 重定向时间的 output 并将其捕获到变量中。 Assuming you may want to execute more complex commands than ls -R we would normally call sh -c 'exec ' this will give you more options in the future.假设您可能想要执行比 ls -R 更复杂的命令,我们通常会调用 sh -c 'exec ' 这将在未来为您提供更多选择。 Thus:因此:
result=$(/usr/bin/time -f "\t%E MM:ss:mm" sh -c 'exec ls -R >/dev/null' 2>&1 tee)
Execution Output:执行 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
here we capture the result as an environment variable在这里,我们将结果捕获为环境变量
>echo $result
0:20.60 MM:ss:mm
finally we arrive at:最后我们到达:
os.popen("/usr/bin/time -f '%E MM:ss:mm' sh -c 'exec ls -R >/dev/null' 2>&1 tee").read()
Execution Out:执行输出:
>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'
hoping the above points you in the right direction.希望以上内容为您指明正确的方向。
this code worked for me on python 2.7此代码在 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)
the output will be like output 会像
5.74 time:2020-07-07 10:53:22
and if you wanted to get usage of memory too you can add this line to your code如果您也想使用 memory ,您可以将此行添加到您的代码中
tot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])
the final code could be this:最终代码可能是这样的:
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)
and here is the output:这是 output:
|| time:11:02:33|| CPU Usage :5.74|| memory :13847/37529
It works with subprocess
but notice that /usr/bin/time
uses stderr它适用于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: Output:
program output: 0:00.00 M:ss:mm, 100% CPU
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.