[Tutor] Capture command output

Alan Gauld alan.gauld at freenet.co.uk
Fri Nov 4 01:03:44 CET 2005


> 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.

You can do the heavy lifting yourself using a combination 
of pipe(), fork(), dup2() and exec() from the os module.

Pseudo code:

# create pipes for stdin/out for our two processes.
p1 = pipe()
p2 = pipe()

# clone the process
pid = fork()
if pid:  # this is the parent process
    close(p1[1])
    close(p2[0])
    dup2(p1[0],0)   # duplicate stdin
    dup2(p2[1],1)   # stdout
else:    # in the child
    close(p1[0])
    close(p2[1])
    dup2(p2[0],0)   # duplicate stdin
    dup2(p1[1],1)   # stdout
    execv(prog,args)

Now we can read and write to the child process using the pipes
to access stdin/stdout.

This is basically what popen does but also gives us access to the 
pid of the child process so that we can send a kill message - which 
was the original requirement!!

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list