0

In executing a time command in bash (Ubuntu 18.04, python 3.6):

$ /usr/bin/time -f '%E' sleep 1
0:01.00

It returns the meausred time as expected. But with subprocess.run() returns empty for the same command:

>>> subprocess.run("/usr/bin/time -f '%E' sleep 1", stdout=subprocess.PIPE, shell = True)
0:01.00
CompletedProcess(args="/usr/bin/time -f '%E' sleep 1", returncode=0, stdout=b'')

I'm not very familiar with the parameters of the function, and my questions are:

Why is the return from subprocess.run() empty?

What's the correct way to use subprocess.run() here?

thor
  • 21,418
  • 31
  • 87
  • 173

1 Answers1

2

time prints its results to standard error, not standard output.

You also don't need or want the shell here.

r = subprocess.run(["/usr/bin/time", "-f", "%E", "sleep", "1"],
    stdout=subprocess.PIPE, stderr=subprocess.PIPE,
    # We expect textual output
    universal_newlines=True,
    # Properly raise an error on failure
    check=True)
print(r.stderr)

Perhaps you should use Python's timing facilities instead, though.

tripleee
  • 175,061
  • 34
  • 275
  • 318