The popen2 module
This module allows you to run an external command and access stdin and stdout (and possibly also stderr) as individual streams.
In Python 1.5.2 and earlier, this module is only supported on Unix. In 2.0, the functions are also implemented on Windows.
Example: Using the popen2 module to sort strings
# File: popen2-example-1.py import popen2, string fin, fout = popen2.popen2("sort") fout.write("foo\n") fout.write("bar\n") fout.close() print fin.readline(), print fin.readline(), fin.close()
bar foo
The following example shows how you can use this module to control an existing application.
Example: Using the popen2 module to control gnuchess
# File: popen2-example-2.py import popen2 import string class Chess: "Interface class for chesstool-compatible programs" def __init__(self, engine = "gnuchessc"): self.fin, self.fout = popen2.popen2(engine) s = self.fin.readline() if s != "Chess\n": raise IOError, "incompatible chess program" def move(self, move): self.fout.write(move + "\n") self.fout.flush() my = self.fin.readline() if my == "Illegal move": raise ValueError, "illegal move" his = self.fin.readline() return string.split(his)[2] def quit(self): self.fout.write("quit\n") self.fout.flush() # # play a few moves g = Chess() print g.move("a2a4") print g.move("b2b3") g.quit()
b8c6 e7e5