pns
pns

Reputation: 423

Python run command line (time)

I want to run the 'time' unix command from a Python script, to 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

Upvotes: 1

Views: 1329

Answers (2)

CruiZen
CruiZen

Reputation: 182

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.

Upvotes: 0

Josh Wright
Josh Wright

Reputation: 2505

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()

Upvotes: 3

Related Questions