首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用子流程与python交互

使用子流程与python交互
EN

Stack Overflow用户
提问于 2022-10-12 17:46:16
回答 1查看 67关注 0票数 1

我尝试使用这样的子流程模块与python解释器进行交互:

代码语言:javascript
运行
复制
import subprocess


def start(executable_file):
    return subprocess.Popen(
        executable_file,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)


def read(process):
    return process.stdout.readline().decode("utf-8").strip()


def write(process, message):
    process.stdin.write(f"{message.strip()}\n".encode("utf-8"))
    process.stdin.flush()


def terminate(process):
    process.stdin.close()
    process.terminate()
    process.wait(timeout=0.2)


process = start("python")
while True:
    write(process, input())
    print(read(process))
terminate(process)

但它似乎陷入了僵局。

如果有人知道如何使用python代码与python交互并恢复stdout,则使用流模式的stderr。

EN

回答 1

Stack Overflow用户

发布于 2022-10-12 18:42:49

您需要使用communicate()而不是read()write(),否则会导致死锁。

请参阅页面中部的红色警告突破。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74046059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档