[Tutor] Capture command output

Hugo González Monteverde hugonz-lists at h-lab.net
Thu Nov 3 21:35:34 CET 2005


Hi,

Here's the docs for the popen2 module in python 2.2, the Popen2 object 
allows you to get the pid. The popen2() call allows you to get the 
output in a filehandle.

http://www.python.org/doc/2.2.3/lib/module-popen2.html

You cannot run any function at all in your script after you do the exec 
call, it is no longer your program, but the one you exec-ed. popen 
actually runs the  subprocess, you don't have to call it manually. Popen 
is the most used way to get the output, and looks like it is the only 
one in Python 2.2.

Here's an example.


 >>> import popen2
 >>> myobj = popen2.Popen3('/bin/ls')
 >>> dir(myobj)
['__doc__', '__init__', '__module__', '_run_child', 'childerr', 
'fromchild', 'pid', 'poll', 'sts', 'tochild', 'wait']
 >>> myobj.pid
3033
 >>> output = myobj.fromchild.read()
 >>> output
'Changelog\nblankcursor\ndaemon.py\ndaemon.pyc\nl_index.txt\nl_sec.txt\nloadlin16c.txt\nloadlin16c.zip\nmypipa\nnewlooper.py\nxorg.conf.new\n'
 >>> myobj.wait()
0



Johan Geldenhuys wrote:
> The version of python that I have is 2.2.2 and I can't upgrade, sorry. 
> As far as I know this only from version 2.4.2??
> 
> Johan
> 
> Kent Johnson wrote:
> 
>>Johan Geldenhuys wrote:
>>  
>>
>>>I've been musy with the os command on how to kill a process. That's been 
>>>sorted out to an extend. Many thanks for your input.
>>>
>>>Now I have a question in the same direction:
>>>
>>>I use os.execpv(cmd, [cmd, args]). That executes the command that have 
>>>output. This was the best way of getting the pid and killing the process 
>>>after a certain time.
>>>
>>>How do I capture that output to a file?
>>>Can I use os.popen() or something like that after I did the os.execvp() 
>>>execution or is there a standard way of putting any output in a file/
>>>    
>>>
>>
>>Have you tried using subprocess.Popen()? It supports capturing output of the child process and it gives access to the pid of the child.
>>
>>Kent
>>
>>  
>>
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list