0

I want to run a subprocess.Popen('echo 1; sleep 1; echo 1', shell=True, stdout=?) in a way I would have the output appear (at run time) and also be able to save it into a PIPE or file.

So far I ran with proc = subprocess.Popen('echo 1; sleep 1; echo 1', shell=True, stdout=PIPE, stderr=PIPE) giving me the 2nd requirement, and then I would print the result of out, err = proc.communicate(), but using communicate is blocking, and so, if the Popen takes a long time, I can't show the output and that's unacceptable.

Can I somehow leave the stdout= field empty (to enable console output) and also copy output to a PIPE?

Update. This is not the same as Python Popen: Write to stdout AND log file simultaneously because I want to be able to access the oputput during the run, and the solution there suggests accessing proc.stdout which is blocking until the end of the run.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • I don't understand `communicate` is blocking ? What is it blocking? – Rahul May 26 '19 at 10:42
  • In [4]: subprocess.Popen.communicate? Signature: subprocess.Popen.communicate(self, input=None) Docstring: Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. **Wait for process to terminate**. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). – CIsForCookies May 26 '19 at 10:43
  • 1
    @CIsForCookies If the duplicate doesn't answer your question, then what are you trying to do? If you don't want to block when reading stdout, then how do you want to read it? Reading `stdout` doesn't force you to wait for the process completion - you can pause/stop at any newline. –  May 26 '19 at 19:30
  • How can I read stdout? the only way I found was `for line in proc.stdout` which will block until proc has finished... – CIsForCookies May 27 '19 at 10:45

0 Answers0