0

I am trying to run a shell command via subprocess.run, and I would like to redirect the output to a file, but also display it on stdout at the same time.

I have not found a way to do it, is this possible in a pure Python script?

It would be equivalent to doing some_command | tee file.txt in bash.

I could always write a wrapper bash script that will invoke the python script and call tee, but would be nice if Python had a way to do this directly.

darxsys
  • 1,560
  • 4
  • 20
  • 34

1 Answers1

0

You can capture the output and send to stdout and a file.

Python 3.7+:

r = subprocess.run(cmds, capture_output=True, text=True)

Python 3.5+:

r = subprocess.run(cmds, stdout=PIPE, stderr=PIPE)
stdout = r.stdout.decode("utf-8") # specify encoding

Example

import subprocess
r = subprocess.run(['ls'], capture_output=True, text=True)
print(r.stdout)
with open('a.txt','w') as f:
    f.write(r.stdout)
Peter Xie
  • 19
  • 1
  • 4
    This doesn't work if I want to print the lines out while the command is running and producing output. – darxsys Jul 27 '20 at 22:17