Osada Lakmal
Osada Lakmal

Reputation: 901

processing output of time command in a python script

I am trying to write a python script that benchmarks several pieces of code. The issue is when the script is run the output of the command id different from what I would get it I run it directly at bash prompt.

Here is the code for the python script

import subprocess
import re
import os
app = os.getcwd() + "/" + "myapp"
testPopen = subprocess.Popen(args=['/usr/bin/time',app],
    stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=False) 
testPopen.wait()

Here is the ouput of above code

    real        1.0
    user        0.8
    sys         0.0

Upvotes: 1

Views: 389

Answers (1)

unutbu
unutbu

Reputation: 879531

When you run time myapp from the bash prompt, you are using bash's time command. (Type help time to see that bash understands it as a bash command.)

When you run the python script you are using /usr/bin/time, which is a different program. (Type man time or which time to see that time is also a program. How confusing!)

To get the python script to use the bash time command:

import shlex
testPopen = subprocess.Popen(shlex.split('bash -c "time {a}"'.format(a = app)),
    stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=False) 
out,err = testPopen.communicate()
print(err)

Upvotes: 2

Related Questions