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.

2
  • Have you considered using 'subprocess.Popen()', and than 'subprocess.Communicate()'? Commented Jul 25, 2020 at 6:13
  • Yes, thank you, I didn't find that. Commented Jul 27, 2020 at 22:22

1 Answer 1

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work if I want to print the lines out while the command is running and producing output.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.