Read a few lines from subprocess .Popen.stdout

I changed the source code from the standard Fred Lundh Python library. The original source uses popen2 to communicate with the subprocess, but I changed it to use subprocess.Popen () as follows.

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

It seems to work fine, but gnuchess prints a few lines of messages as follows, but with self.fout.readline () it only shows one line.

Thinking ...
... 
RNBQKBNR 

How to get multiple lines of message? readlines () does not work.

ADDED

I tested the code from the movie, but it does not work. I think it is just right that only readline () should work, not readlines () and read (), since no one knows when to stop reading except readline ().

+3
2

gnuchess, 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')
+2

. , , . - -

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

self.fout.readline(). . .

0

Source: https://habr.com/ru/post/1768678/


All Articles