在python中执行linux time命令

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

我想计算在python脚本中执行c程序所花费的时间。我为此使用了os.system()函数。

os.system("{ time ./test.out < inp;} > out 2> exe_time")
  • test.out是我的c可执行文件
  • inp包含c的输入
  • out存储c程序的输出
  • exe_time存储程序的执行时间。

我在exe_time中得到的结果是这样的

0.00user 0.00system 0:00.00elapsed?%CPU(0avgtext + 0avgdata 1416maxresident)k 0inputs + 8outputs(0major + 65minor)pagefaults 0swaps

但是当我在终端中执行{time ./test.out <inp;}> out 2> exe_time时,我会进入exe_time文件

真正的0m0.001s 用户0m0.000s sys 0m0.000s

如何使用python获取第二版输出?

python linux shell time subprocess
2个回答
1
投票

bash调用你的代码,而不是/bin/sh(这是system()的默认代码):

subprocess.Popen(['bash', '-c', '{ time ./test.out < inp;} > out 2> exe_time'])

但请注意,上述代码无法安全地参数化以使用任意文件名。更好的实践实现可能看起来像:

o, e = subprocess.Popen(['bash', '-c', 'time "$@" 2>&1', '_', './test.out'],
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

print("Output from command is:")
sys.stdout.write(o + "\n")
print("Output from time is:")
sys.stdout.write(e + "\n")

注意:

  • 我们明确地调用bash,从而确保使用它的time的内置实现。
  • 从shell脚本带外传递参数可以安全地将任意参数传递给正在运行的脚本,而不必担心这些参数是否包含尝试的shell注入攻击。
  • 在shell脚本中重定向2>&1可确保test.out编写的任何stderr与其他输出连接,而不是与time命令的输出混合。
  • 如果我们确实想要将输出重定向到文件,那么更好的练习方法是使用Python,就像使用stdout=open('out', 'w'), stderr=open('exe_time', 'w')一样。

1
投票

qazxsw poi使用qazxsw poi。 Bash有自己的qazxsw poi内置,它使用而不是os.system()二进制:

/bin/sh

如果您想查看命令执行所需的时间,请使用time

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