子进程check_output缩短我的输出

问题描述 投票:3回答:2

我必须编写几个C程序在几个文件上运行所需的时间:

time ./program filename

到电子表格,并使用subprocess.check_outputstdout作为一个字符串。我应该得到以下内容:

real    0m0.001s
user    0m0.001s
sys     0m0.000s

但我得到:

b'0.00user 0.00system 0:00.00elapsed ?%CPU (0avgtext+0avgdata 
1388maxresident)k\n0inputs+0outputs (0major+60minor)pagefaults 
0swaps\n'

我看到了用户和系统时间,但它们在两位小数后被切断。有没有办法确保输出读取所有3位小数?这是我的代码:

import xlwt
import subprocess

files = ('100KB.txt', '1MB.txt', '10MB.txt', '100MB.txt')
programs = ('./10kBuffer', './step2', './step3', './step4')

command = ['time', programs[0], files[0]]
out = subprocess.check_output(command, stderr=subprocess.STDOUT)
print(out)
python subprocess
2个回答
2
投票

这是因为GNU time使用默认格式字符串,更详细,但你需要-p选项。

引用manual

默认格式字符串是:

%Uuser%Ssystem%Eelapsed%PCPU(%Xtext +%Data%Mmax)k%Iinputs +%Ooutputs(%Fmajor +%Rminor)pagefaults%Wswaps

当给出-p选项时,使用(可移植)输出格式:

real %e
user %U
sys %S

你还需要解码输出,否则你将获得bytes而不是str,并且不会解释换行符。例如:

>>> print(b'hello\nworld\n')
b'hello\nworld\n'
>>> print('hello\nworld\n')
hello
world

所以我会修复你的代码:

command = ['time', '-p', programs[0], files[0]]
out = subprocess.check_output(command, stderr=subprocess.STDOUT)
print(out.decode())

编辑:the other answer似乎通过使用shell内置帮助修复丢失的小数。您可以混合两个答案,以获得所需的输出作为字符串,具有足够的小数。

请注意,除非您想为命令使用探查器,否则您似乎无法做得更好(请参阅How do I get time of a Python program's execution?


2
投票

看起来你在你的python脚本使用的GNU time和在命令行上使用的内置time shell之间会遇到混淆。

这来自GNU time的手册页:

注意:某些shell(例如bash(1))具有内置时间命令,该命令提供的功能少于此处描述的命令。要访问实际命令,您可能需要指定其路径名(类似于/ usr / bin / time)。

基于您期望的输出,看起来您想要内置的bash,它提供3个小数位:

$ bash -c time time

real    0m0.000s
user    0m0.000s
sys     0m0.000s

$ sh -c time time
user    0m0.00s
sys     0m0.00s

$ ksh -c time time
user    0m0.00s
sys     0m0.00s

$ tcsh -c time time
0.016u 0.011s 0:00.02 100.0%    0+0k 0+0io 0pf+0w

因此,为了指定bash内置而不是GNU time,您可以将命令更改为:

command = ['bash', '-c', 'time', programs[0], files[0]]

你应该得到你期望的输出。

© www.soinside.com 2019 - 2024. All rights reserved.