Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get output from subprocess.Popen(). proc.stdout.readline() blocks, no data prints out

I want output from execute Test_Pipe.py, I tried following code on Linux but it did not work.

Test_Pipe.py

import time while True :     print "Someting ..."     time.sleep(.1) 

Caller.py

import subprocess as subp import time  proc = subp.Popen(["python", "Test_Pipe.py"], stdout=subp.PIPE, stdin=subp.PIPE)  while True :     data = proc.stdout.readline() #block / wait     print data     time.sleep(.1) 

The line proc.stdout.readline() was blocked, so no data prints out.

like image 248
wearetherock Avatar asked Sep 07 '09 10:09

wearetherock


People also ask

How does subprocess Popen work?

The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.

What is the difference between subprocess call and Popen?

Popen is more general than subprocess. call . Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

What is pipe in Popen?

Popen() takes two named arguments, one is stdin and the second is stdout. Both of these arguments are optional. These arguments are used to set the PIPE, which the child process uses as its stdin and stdout. The subprocess. PIPE is passed as a constant so that either of the subprocess.

What is Popen in Python?

Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.


1 Answers

You obviously can use subprocess.communicate but I think you are looking for real time input and output.

readline was blocked because the process is probably waiting on your input. You can read character by character to overcome this like the following:

import subprocess import sys  process = subprocess.Popen(     cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE )  while True:     out = process.stdout.read(1)     if out == '' and process.poll() != None:         break     if out != '':         sys.stdout.write(out)         sys.stdout.flush() 
like image 76
Nadia Alramli Avatar answered Oct 18 '22 20:10

Nadia Alramli