get the output of a cmd via popen2

Peter Hansen peter at engcorp.com
Sat Aug 25 22:45:54 EDT 2001


Rajarshi Guha wrote:
> 
> i,o = os.popen2(cmd)
> 
> where cmd is the string that represents the command. But on printing o all
> I get is an object representation like:
> 
> <open file '(fdopen)', mode 'r' at 0x810d9f8>
> 
> Any suggestions as to whats going wrong and how to fix it?

Nothing is going wrong.  This is what is supposed to happen.

Except that you haven't finished yet... you are supposed 
to take 'o' and read from it, exactly as you would have
if you had stored the output in a file ahead of time and
were now trying to read it in using open() and read().

>>> import os
>>> i,o = os.popen2('type c:\\autoexec.bat')
>>> print o.read()
@ECHO OFF
SET BLASTER=A220 I5 D1 T4
call c:\bin\basepath c:\bin c:\jdk1.2\bin
set temp=c:\temp
set tmp=%temp%
set dircmd=/ogn
set home=c:\users\peter
set pythonhome=c:\a\python
doskey >nul

Note that you could also use readline() or readlines(),
or many other things which work on readable files.

The 'i' variable contains a reference to a writable
file object, which lets you send input to the command
you are running, if it expects any.

Basically, 'i' connects you to the stdin of the command,
and 'o' connects you to the stdout of the command, but
it's up to you to write to and read from those file
objects.

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list