Read python STDOUT in real time

My code looks like this: basically this module will execute the required command and run its output line by line, but in my case when the command is run it only takes a few seconds to return to the command line and then -.stdout.read (1) hangs if I run a normal command using this it prints everything as expected. but in the specific case, when the command prints somthing for STDOUT and then takes a while to get back to the prompt, it hangs. Please, help

New code:

def run_command(shell_command):
'''run the required command and print the log'''
child = subprocess.Popen(shell_command, shell=True,stdout=subprocess.PIPE)
(stdoutdata, stderrdata) = child.communicate()
print stdoutdata

print "Exiting.."

      

Mistake:

  File "upgrade_cloud.py", line 62, in <module>
stop_cloud()
File "upgrade_cloud.py", line 49, in stop_cloud
run_command(shell_command)
 File "upgrade_cloud.py", line 33, in run_command
 (stdoutdata, stderrdata) = child.communicate()
 File "/usr/lib/python2.6/subprocess.py", line 693, in communicate
stdout = self.stdout.read()
KeyboardInterrupt

      

+3


source to share


1 answer


Here is your problem:

child.wait()

      



This line makes Python wait for the child to finish. If the child process tries to print a lot of data to stdout, it will block waiting for Python to read the specified data. Since Python is waiting for a child process and a child process is waiting for Python, you get a dead end.

I would recommend instead subprocess.Popen

subprocess.check_output()

. You can also use a method Popen.communicate()

instead of a method .wait()

.

+3


source







All Articles