popen help

exarkun at intarweb.us exarkun at intarweb.us
Fri Nov 12 16:40:13 EST 2004


On Fri, 12 Nov 2004 12:19:08 -0800, Jason Zheng <jzheng at jpl.nasa.gov> wrote:
>exarkun at intarweb.us wrote:
> > On Fri, 12 Nov 2004 11:29:46 -0800, Jason Zheng <jzheng at jpl.nasa.gov> wrote:
> > 
> >>I'm trying to open a subshell to run some csh commands, and I want to 
> >>connect the stdout of the subshell to the main stdout:
> >>
> >>sub = Popen4('csh -f')
> >>sub.tochild.write('source source.me\n')
> >>sub.tochild.write('runthis\n')
> >>sub.tochild.close()
> >>
> >>for x in sub.fromchild.readlines():
> >>   print x
> >>
> > 
> > 
> >>>>import os, time
> >>>>for x in iter(os.popen('for x in `seq 3`; do echo $x; sleep 1; done').readline, ''):
> > 
> > ...     print time.time(), x,
> > ... 
> > 1100290304.55 1
> > 1100290305.56 2
> > 1100290306.56 3
> > 
> >   The difference is that readline() returns one line whereas readlines() returns all of the lines.  Since you cannot know what all the lines are until you have read all of the data, it cannot return until the child process exits.
> > 
> >   Jp
> Jp,
> 
> I doubt that's gonna resolve the problem I have tho. Suppose I send one 
> command which doesn't not have the 'sleep' but prints some output line 
> periodically, wouldn't I have to wait till the end of the execution to 
> see any output?
> 

  The sleep is running in the spawned process to make it more apparent that periodic output appears immediately in the Python process.

  Give it a try in your application.  I think you will find it behaves as you wish.

  Jp



More information about the Python-list mailing list