1

如果我打开一个 .exe 文件,我正在做一个项目。该文件将打开一个终端,我想在其中输入命令并保存输出。我现在正在使用的代码返回一个错误,即 ActiveEngine2.stdin.write("go depth 5") 需要类似字节的对象而不是 'str'。

import subprocess

SFPath = "stockfish_14.1_win_x64_avx2\stockfish_14.1_win_x64_avx2.exe"

ActiveEngine = subprocess.run([SFPath, "position startpos move e2e4 e7e5"], capture_output=True)
print(ActiveEngine.stdout.decode())
ActiveEngine2 = subprocess.Popen(SFPath, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

ActiveEngine2.stdin.write("go depth 5")
print(ActiveEngine2.stdout.readline().strip())

我能够打开该文件,但我不知道如何将输入放入其中,并且就此而言,从中获取输出。Stack Overflow( Stockfish 和 Python )上还有一篇关于此类问题的帖子,我已经尝试过他们使用的代码,但由于某种原因它不起作用。公平地说,我确实改变了路径,当然,也许还有一两件事(在尝试了原来的之后),但它不起作用并且没有完成 while 循环(或者,据我所知,迭代它完全没有。)

import subprocess, time
import os


#The path to StockFish

SFPath = "stockfish_14.1_win_x64_avx2\stockfish_14.1_win_x64_avx2.exe"


engine = subprocess.Popen(SFPath, universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

def put(command):
    print('\nyou:\n\t'+command)
    engine.stdin.write(command+'\n')

def get():
    # using the 'isready' command (eng has to answer 'readyok')
    # to indicate current last line of stdout
    engine.stdin.write('isready\n')
    print('\nengine:')
    while True:
        print("This will print each time it iterates")
        text = engine.stdout.readline().strip()
        if text == 'readyok':
            print("this is printed when get the program has completed the answer")
            break
        if text != 'readyok':
            #note I have tried '' like the original code and it doesn't work either
            print("This will print whenever the engine output doesn't equal readyok")
            print('\t'+text)

put('go depth 15') 
get()
put('eval')
get() 
put('position fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') 
get()

作为参考,输出是

you:
    go depth 15

engine:
This will print each time it iterates
This will print whenever the engine output doesn't equal readyok
    Stockfish 14.1 by the Stockfish developers (see AUTHORS file)
This will print each time it iterates

另一个可能对人们有所帮助的消息是,我手动关闭了打开它的 Stock Fish 终端,它将永远重复,据我所知

This will print each time it iterates
This will print whenever the engine output doesn't equal readyok

我无法理解子流程的工作原理以及如何提供/获取输入/输出。我正在使用 Windows 10、Python 3.10.0 和 StockFish 14.1。

4

0 回答 0