popen2

Donn Cave donn at u.washington.edu
Tue Aug 12 18:57:50 CEST 2003


In article <f3ff61d9.0308120508.5ecd44f at posting.google.com>,
 guy.flowers at Machineworks.com (Guy) wrote:

> The unix equivalant is something like this :
> 
> from popen2 import popen2
> output, input = popen2("csh")
> # Sets the enviroment.
> input.write("setenv DISPLAY doors:0.0\n")
> 
> input.writeinput.write(f_mwtest_exe_str + " " + f_mwtest_args + " " +
> os.path.dirname(f_testlwc_str) + " " + f_testlwc_str + "\n")
> 
> print "finished"
> process the output from the test file.
> 
> 
> The problem is at the moment I can't get the process to stop and wait
> until the exe has finished executing, the python script executes
> everything and then the test file is executed afterwards. I'm thinking
> that there must be a switch on the csh or sh command to stop this
> happening but I don't know what it is. The unix machines that I'm
> working on are all different plat types, so the platform type proberly
> won't help you.

Try something like
   status = input.close()
   result = output.read()
   if status is None:
       print 'success:', repr(result)
   else:
       print 'error exit', status, repr(result)

The close() is the important part:

  1. flush your buffer so data actually goes to the shell
  2. closes the shell's input so it doesn't stay around
        waiting for more.
  3. returns exit status for the shell process, or None
       if the exit status is 0.  (This won't work so well
       for rsh.)

While I'm at it, I would recommend that you use "sh" instead
of "csh", because in the end it will give you less grief with
bugs and misfeatures.  "setenv x v" -> "x=v export x" if you
do this.  I would also recommend popen2("sh 2>&1") so that
the piped output includes error/diagnostic output.

   Donn Cave, donn at u.washington.edu




More information about the Python-list mailing list