开发者

Python run command line (time)

开发者 https://www.devze.com 2022-12-27 02:15 出处:网络
I want to run the \'time\' unix command from a Python script, to开发者_JS百科 time the execution of a non Python app. I would use the os.system method.

I want to run the 'time' unix command from a Python script, to开发者_JS百科 time the execution of a non Python app. I would use the os.system method. Is there any way to save the output of this in Python? My goal is to run the app several times, save their execution times and then do some statistics on them.

Thank You


You really should be using the subprocess module to run external commands. The Popen() method lets you specify a file object where stdout should go (note, you can use any Python object that behaves like a file, you don't necessarily need to write it to a file).

For instance:

import subprocess
log_file = open('/path/to/file', 'a')

return_code = subprocess.Popen(['/usr/bin/foo', 'arg1', 'arg2'], stdout=log_file).wait()


You can use the timeit module to time code snippets (say, a function that launches external commands using subprocess module as described in the answer above) and save the data to a csv file. You can do statistics on the csv data using a stats module or externally using Excel/ LogParser/ R etc.

Another approach is to use the hotshot profiler that does the profiling and also returns stats that you can either print using print_stats() method or save to a file by iterating over.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号