【发布时间】:2014-12-12 07:20:41
【问题描述】:
我一直在使用time 命令在我的shell 中进行一些手动基准测试。我想通过编写一个 python 脚本来扩展我的基准测试,该脚本既可以自动化测试,又可以让我访问时间数据,以便我可以以我选择的格式(可能是 csv)记录它。我看到有 timeit 模块,但这似乎更适用于对 python 代码进行基准测试,我在这里尝试对在命令行中运行的程序进行基准测试。
这是我一直在手动做的:
time program -aflag -anotherflag
我最初尝试在脚本中实现这一点如下:
cmnd = ['time', 'program', 'aflag', 'anotherflag']
p = subprocess.Popen(cmnd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate
print out
print err
我可以很好地访问time 的输出——它被传送到stderr,但是我没有在stdout 中得到program 的输出。如果我从cmnd 中删除time 并将shell=False 更改为True,然后我会在stdout 中获得程序的输出——但显然不是time 的输出,这就是重点。
cmnd = ['program', 'aflag', 'anotherflag']
p = subprocess.Popen(cmnd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate
print out
print err
如果我用shell=True 将time 添加回cmdnd,我会得到时间的输出,但program 实际上并没有运行。
我怎样才能让两者都工作?
【问题讨论】:
-
请复制粘贴一个 actualll 简短的独立程序来演示您的错误。请不要只是输入它,而是测试它,运行它,然后复制粘贴它。谢谢。见stackoverflow.com/help/mcve
-
shell 中的
time命令不显示结果!!它只是显示时间real,os,user! -
修复测试程序中的语法错误并将
cmnd替换为cmnd = ['time', 'ls', '-s', '-h']后,我在out和err中都得到了正确的结果。 This link 包含我的程序。 -
那么你的程序是什么?它是python代码吗?还是...?
-
@Kasra:比这更糟糕;
/usr/bin/time程序和不同 shell 中名为time的 shell 内建函数在处理程序的输出和/或错误方面都不同,这使得新手在围绕命令编写代码时非常困惑……
标签: python shell time stdout benchmarking