You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python程序调用lc0.exe并启动时执行指定命令?

解决Leela Chess Zero接入Python后端的输入问题

你的代码核心问题是没有为子进程配置可写入的标准输入管道,导致go nodes 1000命令无法传递给lc0.exe。另外几个小细节也需要调整,以下是修正方案:

修正后的代码

import subprocess

def run_lc0():
    # 配置子进程,开启stdin管道用于发送命令,同时捕获stdout和stderr
    p = subprocess.Popen(
        "C:/Users/newli/leela/lc0.exe",
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True  # 用文本模式替代手动encode/decode,更方便
    )
    # 发送命令并获取输出、错误信息,同时等待进程结束
    stdout, stderr = p.communicate(input="go nodes 1000\n")
    print("输出结果:")
    print(stdout)
    if stderr:
        print("错误信息:")
        print(stderr)

run_lc0()

关键改动说明

  • 添加stdin=subprocess.PIPE:允许Python向lc0.exe的标准输入写入命令,这是传递指令的前提。
  • 使用text=True:让subprocess自动处理字符串和字节的转换,无需手动调用encode()/decode()。
  • 给命令加\n:lc0.exe的交互模式需要换行符来确认执行命令,否则会一直等待输入。
  • 捕获stdout和stderr:方便你查看Leela的计算结果或排查运行错误。

持续交互的进阶方案

如果你的项目需要和lc0.exe持续交互(比如多次发送命令),不要用communicate()(它会等待进程结束),可以直接操作stdin和stdout:

import subprocess

def interactive_lc0():
    p = subprocess.Popen(
        "C:/Users/newli/leela/lc0.exe",
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        bufsize=1,  # 行缓冲,实时获取输出
        universal_newlines=True
    )
    
    # 发送第一条命令
    p.stdin.write("go nodes 1000\n")
    p.stdin.flush()  # 强制刷新缓冲区,确保命令发送
    
    # 读取输出(示例:读取10行)
    for _ in range(10):
        line = p.stdout.readline()
        print(line.strip())
    
    # 发送第二条命令
    p.stdin.write("position startpos moves e2e4\n")
    p.stdin.flush()
    
    # 后续可以继续交互,最后记得关闭进程
    p.stdin.close()
    p.wait()

interactive_lc0()

内容的提问来源于stack exchange,提问作者AlphanumericUsername

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 16:13:25