Python:将命令输出存储在变量中

Python:将命令输出存储在变量中,python,Python,我想用/usr/bin/time工具测量命令的时间和cpu使用情况。但是当我执行os.popen(“/usr/bin/time-f\t%E MM:ss:MM ls-R”).read()时,它还存储ls-R的输出。如何仅存储/usr/bin/time输出 我还尝试了子流程,但也不起作用 out = subprocess.Popen(['/usr/bin/time', '-f', '"\t%E MM:ss:mm"', 'ls', '-R'], stdout=sub

我想用
/usr/bin/time
工具测量命令的时间和cpu使用情况。但是当我执行
os.popen(“/usr/bin/time-f\t%E MM:ss:MM ls-R”).read()
时,它还存储
ls-R的输出。如何仅存储
/usr/bin/time
输出

我还尝试了
子流程
,但也不起作用

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    
输出:

.:
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
program output:         0:00.00 M:ss:mm,        100% CPU

您需要将命令的输出发送到
/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
,然后重定向来自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
>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'
这里我们将结果捕获为一个环境变量

>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()
执行输出:

>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
>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)
输出将类似于

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

它与
子流程一起工作
,但请注意
/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"))
输出:

.:
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
program output:         0:00.00 M:ss:mm,        100% CPU

您将如何在控制台中执行此操作?如果您不在PythonI中,那么为terminal命令添加了I/O,但我不确定您的意思,您只是在调用terminal命令。如果您不想通过Python来实现这一点,而只是想获得预期的输出,那么您会编写什么命令?我需要将时间存储在变量中。在终端中看起来很不错,但如何将其存储为variable@René-如何在Python中为变量赋值?(提示:它涉及到
=
)我知道分配是如何工作的,但当我这样做时,
out=os.popen(“/usr/bin/time-f\t%E MM:ss:MM ls-R>/dev/null 2>&1”)。read()
然后
打印(out)
它会打印一个空白line@RenéI更新了答案,以解决如何将时间输出分配给shell变量的问题。注意安全。