Python 从subprocess.Popen.stdout读取多行
我修改了Fred Lundh的Python标准库中的源代码。 原始源代码使用popen2与子流程通信,但我将其更改为使用subprocess.Popen(),如下所示Python 从subprocess.Popen.stdout读取多行,python,subprocess,Python,Subprocess,我修改了Fred Lundh的Python标准库中的源代码。 原始源代码使用popen2与子流程通信,但我将其更改为使用subprocess.Popen(),如下所示 import subprocess import string class Chess: "Interface class for chesstool-compatible programs" def __init__(self, engine = "/opt/local/bin/gnuchess"):
import subprocess
import string
class Chess:
"Interface class for chesstool-compatible programs"
def __init__(self, engine = "/opt/local/bin/gnuchess"):
proc=subprocess.Popen([engine],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
self.fin, self.fout = proc.stdin, proc.stdout
s = self.fout.readline() <--
print s
if not s.startswith("GNU Chess"):
raise IOError, "incompatible chess program"
def move(self, move):
...
my = self.fout.readline() <--
...
def quit(self):
self.fin.write("quit\n")
self.fin.flush()
g = Chess()
print g.move("a2a4")
print g.move("b2b3")
g.quit()
导入子流程
导入字符串
国际象棋:
“chesstool兼容程序的接口类”
def uuu init uuuu(self,engine=“/opt/local/bin/gnuchess”):
proc=subprocess.Popen([engine],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
self.fin,self.fout=proc.stdin,proc.stdout
s=self.fout.readline()我会在它到达时读取它的输出。当流程结束时,子流程模块将负责为您清理。你可以这样做-
l = list()
while True:
data = proc.stdout.read(4096)
if not data:
break
l.append(data)
file_data = ''.join(l)
所有这些都是对self.fout.readline()
的替代。我没有试过。但是应该处理多行。要与gnuchess交互,我会使用
l = list()
while True:
data = proc.stdout.read(4096)
if not data:
break
l.append(data)
file_data = ''.join(l)
import pexpect
import sys
game = pexpect.spawn('/usr/games/gnuchess')
# Echo output to stdout
game.logfile = sys.stdout
game.expect('White')
game.sendline('a2a4')
game.expect('White')
game.sendline('b2b3')
game.expect('White')
game.sendline('quit')