Getting both PID and output from a command

Noah noah at noah.org
Fri Mar 19 21:06:11 EST 2004


hugh at brokenpipefilms.com (Hugh Macdonald) wrote in message news:<3cc4824d.0403190259.1e06a578 at posting.google.com>...
> I'm calling a command from within a python script and I need to be
> able to both catch the output (stdout and stderr) from it and also
> have the PID (so that I can kill it)
> 
> I can do one or other of these, but I can't find any way to do them
> both at the same time.
> 
> So far, I've got the following options:
> 
> 
> To get the output from the command:
> 
> >>> fdin, fdout, fderr = os.popen3(command)
> 
> 
> Or to get the PID so that I can kill it:
> 
> >>> pid = os.spawnvp(os.P_NOWAIT, command.split()[0], command.split())
> 
> 
> I've tried doing the following to grab stderr (I only need stderr, not
> stdout in this case)
> 
> >>> fderr = os.pipe()
> >>> sys.stderr = fderr
> >>> pid = os.spawnvp(os.P_NOWAIT, command.split()[0], command.split())
> 
> But this doesn't seem to help.... It still just outputs stderr to the
> terminal and when I try to do fderr.read(1) I don't get anything...
> 
> Any help would be very welcome
> 
> 
> Hugh Macdonald

Hi,

The Pexpect library lets you run external commands. 
You get output from a command and you can get the pid.
    http://pexpect.sourceforge.net/
You should be able to write code like this:

import pexpect
child = pexpect.spawn (command.split()[0], command.split())
print child.pid
try:
    print child.read()
except pexpect.TIMEOUT:
    child.kill (9)

One problem is that the stdout and stderr are merged into a single stream.
This is a limitation of the Python pty library. Oops...
You will still be able to read the error, but you can't read it
separately from stdout.

Note, I wouldn't trust using a pipe. You will not see any data on the pipe
until the child decides to flush the pipe. There is no way to force the
child to flush it's stdout (your stdin from your point of view).
Pipes are bad for working with child apps that use the stdio libary.
You need a pty for that.

Yours,
Noah



More information about the Python-list mailing list