The popen2 Module

The popen2 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 3-9 shows you how to sort strings using this module.

Example 3-9. Using the popen2 Module to Sort Strings

File: popen2-example-1.py

import popen2, string

fin, fout = popen2.popen2("sort")

fout.write("foo
")
fout.write("bar
")
fout.close()

print fin.readline(),
print fin.readline(),
fin.close()

bar
foo

Example 3-10 demonstrates how you can use this module to control an existing application.

Example 3-10. 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
":
 raise IOError, "incompatible chess program"

 def move(self, move):
 self.fout.write(move + "
")
 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
")
 self.fout.flush()

#
# play a few moves

g = Chess()

print g.move("a2a4")
print g.move("b2b3")

g.quit()

b8c6
e7e5

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols

Internationalization

Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules



Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net