0

I am trying to have the subprocess module pipe out the stdout in realtime.

This worked when i used a test powershell script to ping google.

###STDOUT gets piped to variable in realtime
with subprocess.Popen(['powershell', ".\pingtest.ps1"],stdout=subprocess.PIPE, bufsize=1,universal_newlines=True) as process:
            for line in process.stdout:
                line = line.rstrip()
                print(line)
                try:
                    ws.send(line+ "\n")
                except:
                    pass

However when I tried to use a python command instead, the stdout waited untill the end of the command.

###STDOUT goes to variable once everything is done which isn't what I want
with subprocess.Popen(['python', "from afile import stdoutfunctiondata; stdoutfunctiondata()"],stdout=subprocess.PIPE,bufsize=1,universal_newlines=True,shell=True) as process:
            for line in process.stdout:
                process.stdout.flush()
                line = line.rstrip()
                print(line)
                try:
                    ws.send(line+ "\n")
                except:
                    pass

Is there a way to change stdout to pipe everything to a variable in a for loop in realtime?

  • Python output is buffered when writing to a pipe. – Barmar Jan 25 '22 at 02:39
  • your comment literally helped me solve my issue. I google your exact words and got to this link: https://stackoverflow.com/questions/107705/disable-output-buffering. This helped me to understand that I can put a `-u` flag in the subprocess call and the output wont be buffered. Thanks again – Kmosp9024792 Jan 25 '22 at 03:02

0 Answers0