如何在 Python 中与国际象棋引擎通信? [英] How to Communicate with a Chess engine in Python?

查看:30
本文介绍了如何在 Python 中与国际象棋引擎通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows 7 上,我可以通过命令行与国际象棋引擎通信.在 Win 7 上使用 Stockfish 的小示例会话:

On Windows 7 I can communicate with a chess engine via command line. Small Example Session with Stockfish on Win 7:

C:
unStockfish>stockfish-x64.exe
Stockfish 2.2.2 JA SSE42 by Tord Romstad, Marco Costalba and Joona Kiiski
quit

C:
unStockfish>

第一行是引擎输出的,'quit' 是我输入的退出引擎的内容(有 我可以做的其他事情,但这对我来说很清楚).

The first line was output by the engine and the 'quit' was what I typed to quit the engine (There are other things I can do, but that's clear to me).

现在我想从 python 与该引擎通信:

Now I want to communicate with that engine from python:

import subprocess
engine = subprocess.Popen(
    'stockfish-x64.exe',
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
)
for line in engine.stdout:
    print(line.strip())
engine.stdin.write('quit
')

我明白了

C:
unStockfish>communicate.py
b'Stockfish 2.2.2 JA SSE42 by Tord Romstad, Marco Costalba and Joona Kiiski'

但它并没有退出引擎(没有 C: unStockfish> 提示),它一直在等待输入.我必须用手关上窗户.似乎没有将我的退出消息(python 脚本的最后一行)写入 stdin.

But it doesn't quit the engine (no C: unStockfish> prompt), it keeps waiting for input. I have to close the window by hand. It seems not to get my quit message (last line of the python script) written to stdin.

换句话说,我可以从 stdout 读取,但是当我写入 stdin 时什么也没有发生.

In other words, I can read from stdout but when I write to stdin nothing happens.

我做错了什么以及如何做对?

What am I doing wrong and how to do it right?

推荐答案

你有一个死锁:子进程正在等待输入,而你的程序正在等待它输出更多行

You've got a deadlock: the subprocess is waiting for input, while your program is waiting for it to output more lines in

for line in engine.stdout:
    print(line.strip())

此循环仅在子进程关闭其 stdout 时停止.

This loop only stops when the subprocess closes its stdout.

这篇关于如何在 Python 中与国际象棋引擎通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆