如何与 python 脚本并行运行“.exe”文件(异步)

问题描述 投票:0回答:1

我正在开发一个国际象棋引擎,其中我使用的引擎存储在.exe文件中,GUI是用python(pygame)制作的,我想通过我正在使用的python访问引擎(.exe文件)子流程库。

我面临的问题是国际象棋引擎需要持续工作而不关闭,格式为:

  • 输入:e4
  • 输出:e5

类似这样的事情,所以根据用户的输入,我需要将输入发送到引擎,然后捕获输出以进行移动。 我希望我的 python 脚本与引擎文件并行运行,同时与引擎来回通信,而不关闭引擎。

import subprocess
p1 = subprocess.run('scid_windows_5.0.2\scid_windows_x64\engines\phalanx-scid.exe',shell=True,capture_output=True)
print(p1.stdout.decode())

在这里,输出仅在 .exe 文件结束(ctrl + Z)后显示,而且我无法向引擎提供输入。 请为我提供一种与引擎通信的安全方式,同时保持 python 脚本运行。

python multithreading operating-system subprocess chess
1个回答
-1
投票
import subprocess

# Create a process without blocking, redirect stdin and stdout into pipes
p = subprocess.Popen(["engine.exe"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

#Send data to the process
p.stdin.write("e2".encode())
#Receive one line of data from the process (will block, if there is no input!)
p.stdout.readline().decode()
© www.soinside.com 2019 - 2024. All rights reserved.