2015-05-16 67 views
0

这个子过程代码在Python 2中完美工作,但在Python 3中完美工作。我该怎么办?子过程在Python 2中工作,但不在Python 3中

感谢,

import subprocess 

gnuchess = subprocess.Popen('gnuchess', stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE) 

# Python 3 strings are Unicode and must be encoded before writing to a pipe (and decoded after reading) 
gnuchess.stdin.write('e4\n'.encode()) 

while True: 
L = gnuchess.stdout.readline().decode() 
L = L[0:-1] 
print(L) 
if L.startswith('My move is'): 
    movimiento = L.split()[-1] 
    break 

print(movimiento) 

gnuchess.stdin.write('exit\n'.encode()) 

gnuchess.terminate() 
+2

当它不起作用时会发生什么?你有例外吗?如果是这样,请包含回溯。如果你有其他行为,请描述它。 – Blckknght

回答

1

最有可能的原因不同的是在缓冲行为的变化,设定bufsize=1,使行缓冲。

为避免手动编码/解码,您可以使用universal_newlines=True启用文本模式(使用locale.getpreferredencoding(False)字符编码解释数据)。

#!/usr/bin/env python3 
from subprocess import Popen, PIPE, DEVNULL 

with Popen('gnuchess', stdin=PIPE, stdout=PIPE, stderr=DEVNULL, 
      bufsize=1, universal_newlines=True) as gnuchess: 
    print('e4', file=gnuchess.stdin, flush=True) 
    for line in gnuchess.stdout: 
     print(line, end='') 
     if line.startswith('My move is'):    
      break 
    print('exit', file=gnuchess.stdin, flush=True) 

你不需要调用gnuchess.terminate()如果gnuchess接受exit命令。

直到'我的举动是'这句话,看起来很脆弱。调查gnuchess是否提供具有更严格输出间隔的批处理模式。

相关问题