Tkinter -> spawn external cmd -> return stdout and stderr to back Tkinter

Eric Brunel eric.brunel at pragmadev.com
Wed Mar 27 05:20:27 EST 2002


Fabien Henon wrote:
[snip]
> I use 'spawnv' to fire up POV to start it as a new process. Which
> command should I use to get interactive stdout and stderr back to my
> Tkinter
> application.(do you have any running examples of popen ? the doc is not
> clear)

I'd use popen3, popen4 or popen (like you apparently tried to do...). The 
one you choose depends on what you want to do with the command's stdin, 
stdout and stderr. The simplest is popen4, which returns two opened pipes: 
one opened for writing on the external command's stdin (which you 
apparently won't need), the other opened on the external command's stdout 
and stderr. These pipes are then manipulated like any file opened with the 
same mode. Try:

cmdIn, cmdOut = os.popen4("ls")
print cmdOut.readlines()

If you need to separate the command's stdout from its stderr, use popen3, 
which returns 3 opened pipes: one on the command's stdin (opened for 
writing), one on the command's stdout and one on its stderr (both opened 
for reading). Try:

cmdIn, cmdOut, cmdErr = os.popen3("grep foo *")
print cmdOut.readlines()
print cmdErr.readlines()

Be careful with this one! Since you often can't predict in what order the 
command will print to its stdout and stderr, you may encounter deadlocks 
with popen3. Use it only if you're sure that there will be something on 
both stdout and stderr.

You may also mix two of your solutions by using popen with a redirection:

cmdOut = os.popen("command 2> /tmp/cmderr.txt", 'r')
print cmdOut.readlines()

Since you don't use the command's stdin, the plain popen may be enough for 
your needs. With this solution, you get the command's output directly in 
cmdOut, and to get the command's stderr, you just have to read the file 
/tmp/cmderr.txt. As far as I can see, this may be the best solution for 
you're trying to do...

> I also would like to be able to stop the raytrace when it is started.

To do this, you need to use the *classes* Popen3 or Popen4 in the popen2 
module. These classes are used by the popen2/3/4 functions on Unix, and 
have an attribute giving the process id of the running process. So if you 
want to stop it, you just have to kill it using os.kill. See the module 
popen2 in the library reference. My advice would be to have it working with 
the functions before trying to use the classes...

> I heard about subproc. I can't get to find it in ftp.python.org

Don't know anything about that...

HTH. Bonne chance! Tu risques d'en avoir besoin...
 - eric -




More information about the Python-list mailing list