使用python scrip运行程序时,打印shell的time命令结果

2024-10-02 08:29:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python多次运行程序,并将输出写入一个文件中。我正在执行这个简单的代码来测试,其中clwb是一个编译的程序文件:

#!/usr/bin/env python3

from subprocess import time, call,DEVNULL,STDOUT,check_output,CalledProcessError
import shlex

with open("results/output.csv", 'w') as csvfile:

    command_to_execute="time ./clwb"
    call(shlex.split(command_to_execute),stdout=DEVNULL,stderr=STDOUT)
    result=check_output(shlex.split(command_to_execute), universal_newlines=True)
    csvfile.write(result+" \n") 

我正在lunux中用python3命令执行这个python程序。然而,在文件中,我只得到程序本身的输出,而不是time命令的结果,如果直接从shell执行,在程序输出结束时,打印如下内容:

real    0m0.813s
user    0m1.140s
sys     0m0.056s

这个结果对我来说是最重要的,因为我试图评估进程本身的执行时间。你知道吗

我甚至不是python的初学者,这是我以前处理过的唯一代码,所以我不知道是什么原因导致我在文件中看不到time命令的结果,我认为这应该是可行的,特别是如何解决这个问题。你知道吗

更新:通过修改以下行解决

result=check_output(shlex.split(command_to_execute), stderr=STDOUT, universal_newlines=True) 

Tags: 文件to代码命令程序outputexecutetime

热门问题