从subprocess.Popen.stdou中读取多行

2024-05-19 17:04:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我修改了fredlundh的python标准库的源代码。 原始源代码使用popen2与子进程通信,但我将其改为使用子流程.Popen()如下。在

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()

它似乎运行正常,但是gnucess打印出多行消息,如下所示,但是自已阅读线()它只显示一行。在

^{pr2}$

如何获取多行消息?readlines()方法似乎不起作用。在

添加

我测试了movieyoda的代码,但它不起作用。 我认为只有readline()才有效,而不是readlines()和read(),因为除了readline()之外,人们不知道什么时候停止阅读。在


Tags: importselfreadlinemove源代码defprocquit
2条回答

为了与gnucess交互,我将使用pexpect。在

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')

我只会在它到达时读取它的输出。当进程终止时,子进程模块将负责为您清理内容。你可以这样做-

l = list()
while True:
    data = proc.stdout.read(4096)
    if not data:
        break
    l.append(data)
file_data = ''.join(l)

所有这些都是self.fout.readline()的替代品。没试过。但应该处理多行。在

相关问题 更多 >