views:

125

answers:

2

I'm building a wrapper around a server cmd line script that should run indefinitely. What I need to do is to get the current stout without waiting for the subprocess to finish.

I mean, if I run the following, everything works fine:

ls = Popen(["ls"], stdout=PIPE)
output = ls.stdout.read()

But if I do the same with an indefinitelly running program:

server = Popen(["python","-m","SimpleHTTPServer"], stdout=PIPE)
output = server.stdout.read()

It will not come back...

Update: Even

 output = server.stdout.read(1)

hangs...

Do you know if there's a way to capture partial output from a Popen (or similar threading implementation) in an OS independent way?

A: 

i would guess that read() returns the entire contents? If you read a fixed size chunk in a loop you may get better results.

sean riley
Sorry, forgot to mention that doesn't work either: server.stdout.read(1) hangs too.
Santi
+1  A: 

See the solutions here

Ned Deily
Is this cross platform? (it doesn't look like)
Santi
There is a description of the basic problem and a couple of solutions there. If you can modify the running process to do flushes, that is best. If you can't, Alex outlined the pexpect/wexpect trick which should cover both Unix-y and Windows platform. If those don't work and you can't change the way the child process writes/flushes to stdout and stderr, you're likely out of luck.
Ned Deily
@Santi: confirmed -- pexpect on all Unix variants inc. Mac, wexpect on Windows (if you're running on anything else there may or may not be a solution for other peculiar platforms).
Alex Martelli
Alright, I'll check those out to see if I'm lucky :)Tks both.
Santi