Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > streaming Popen.stdout

Reply
Thread Tools

streaming Popen.stdout

 
 
Michele Simionato
Guest
Posts: n/a
 
      02-21-2006
I was experimenting with subprocess.Popen with the following script:

$ cat Popen_ex.py
import sys, subprocess
po = subprocess.Popen([sys.executable, 'hello.py'],
stdout=subprocess.PIPE,
bufsize=0)
for line in po.stdout:
print line,

where hello.py is the following script:

$ cat hello.py
import time
time.sleep(1)
print 'hello'
time.sleep(1)
print 'world'
time.sleep(1)
print '*END*'
time.sleep(1)

It turns out that Popen collects all the output and write everything
together
after 4 seconds, where I would like to print a line every seconds.
How can I get that in a simple way? A Unix-only solution would be fine,
too.


Michele Simionato

 
Reply With Quote
 
 
 
 
Michele Simionato
Guest
Posts: n/a
 
      02-23-2006
Replying to myself ...

I cooked up this solution involving os.pipe and os.fork, but I am not
especially happy with
it; anyway, let me write it. Feedback is welcome, since this was
written very quickly and
I may have missed something. BTW, are there libraries out there doing
something similar?

----

import subprocess
import os, sys, time

class ReadObject(object):
def __init__(self, fileno):
self.fileno = fileno
self._closed = False
self.name = str(self)
def readline(self):
if self._closed : return ''
return ''.join(iter(self.read1, '\n')) + '\n'
def read(self):
return ''.join(iter(self.read1, '\x00'))
def read1(self):
c = os.read(self.fileno, 1)
if c == '\x00':
self._closed = True
return '\n'
else:
return c
def __iter__(self):
return iter(self.readline, '')

class WriteObject(object):
def __init__(self, fileno):
self.fileno = fileno
self.name = str(self)
def write(self, text):
os.write(self.fileno, text)
def flush(self):
pass
def close(self):
self.write('\x00')

def callproc(child, *args,**kw):
"Run the child procedure in a child process"
r, w = os.pipe()
R, W = ReadObject(r), WriteObject(w)
if os.fork(): # parent
return R
else: # child
sys.stdout = W
try:
child(*args, **kw)
finally:
W.close()
sys.exit()

if __name__ == '__main__':
for line in callproc(subprocess.call, [sys.executable,
'hello.py']):
print line,

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Streaming radio options? news@celticbear.com Firefox 3 01-03-2005 05:29 PM
Streaming video senoj Firefox 17 07-30-2004 04:35 AM
Re: Streaming Audio Problem news_naught Firefox 0 07-27-2003 02:24 AM
Re: Streaming Audio Problem Irmen de Jong Firefox 1 07-17-2003 08:01 PM



Advertisments