Controlling processes (popen2)

Daniel Klein DanielK at aracnet.com
Sat Dec 30 18:08:58 CET 2000


First some background info: I've been learning Python seriously now for
about a month and the first real task I am faced with is to write a Python
script which controls a BASIC process. Additionally I have to do the same
thing in Java. (The BASIC process is used to interface with a third party
database [open files, read, write, etc], but this is just fyi.) The script
must be cross-platform but I am testing this on Win2000 as I don't have a
Linux box available at the moment.

The problem is that in Python I have to terminate all output to the BASIC
process with a \r (rather than \n). In Java, I can use either \n or \r.

To illustrate this, here is a simple BASIC program which compiles to a C
executable called say, TESTIT (note that a ':' is used for concatenation
here):

INPUT LINE1
INPUT LINE2
PRINT "LINE1=" : LINE1
PRINT "LINE2=" : LINE2

Here is the companion Python script which controls this process:

import popen2
instream, outstream = popen2.popen2("TESTIT.exe")
outstream.write("dead\n")
outstream.write("parrot\n")
outstream.flush()
print instream.readline(),
print instream.readline(),
outstream.close()
instream.close()

...and here is a similar one in Java:

import java.io.*;
public class Test1 {
  public static void main(String[] args) {
    try {
      Process process = Runtime.getRuntime().exec("TESTIT.exe");
      OutputStreamWriter outstream = new
OutputStreamWriter(process.getOutputStream());
      BufferedReader instream = new BufferedReader(new
InputStreamReader(process.getInputStream()));
      outstream.write("dead\n");
      outstream.write("parrot\n");
      outstream.flush();
      System.out.println(instream.readLine());
      System.out.println(instream.readLine());
      instream.close();
      outstream.close();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

The output from the Python script using the \n is:

LINE1=dead
LINE2=

Notice that it printed the literal text but not the data sent to the input
stream for the second line.

And the corresponding output from Java (which also uses \n):

LINE1=dead
LINE2=parrot

If I change the Python script to use \r, it matches the Java output. Now I
know you're going to say to use \r (and that is what I'm doing), but the
question is, why does Python behave differently?

Any ideas?

Daniel Klein
Portland, OR USA





More information about the Python-list mailing list