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

Python3.6环境下如何与循环运行的Python进程实现交互式IO交互?

问题:与Python进程实时交互输入输出的正确方法

目标程序逻辑(功能示意)

我有一个逻辑如下的Python程序(非完整代码,仅作功能示意):

while True:
    Number1 = input("What's your first number?")
    Number2 = input("What's your second number?")
    print("Your numbers are: ", Number1, Number2)
    Sum = input("Whats the sum?")
    if Sum == Number1 + Number2:
        print("You win")
        exit()
    else:
        print("You failed, try again!")

需求说明

  • 实际程序逻辑比求和复杂,我无法手动计算结果,需要多次重试
  • 无法修改该程序,仅能执行它
  • 需要编写脚本实现:向程序输入前两个数值→获取程序输出→输入第三个数值→获取输出,循环操作直至成功
  • 当前环境:权限受限的Linux主机,Python版本为3.6

已尝试的方法及问题

方法1:Bash脚本结合Python脚本(临时文件+管道)

通过临时文件和管道传输输入输出,虽能部分运行,但无法正确响应程序输出以调整逻辑:

Bash脚本:

#!/bin/bash
# Create temporary files for communication
output_file=$(mktemp)
# Trap to ensure cleanup of temporary files on script exit
cleanup() {
    rm -f "$output_file"
}
trap cleanup EXIT
# Run the Python scripts with temporary files
python3 /tmp/tmp1/crack.py < "$output_file" | /path/to/python/prog > "$output_file" &
# Wait for the background process to finish
wait
# Display the contents of the output file
cat "$output_file"

对应的crack.py:

#!/usr/bin/env python3

sum_str = ""
answer = ""

while not "You win" in answer:
    print(0)
    print(3)
# Weirdly, works better if I comment the input() lines.
#    input()
#    input()
    sum_str += input()[10]
    print(sum_str)
#    answer = input()

问题:若注释所有input()语句,脚本可运行,但需改为固定次数循环,无法根据程序输出判断终止条件,无法实现动态响应。

方法2:仅使用Python的subprocess模块

#!/usr/bin/python3

from subprocess import PIPE, Popen
import sys

p = Popen([sys.executable, '/path/to/main/python/exec'], stdout=PIPE, stdin=PIPE)

stdout, stderr = p.communicate(input="1\n200\noops\n")
print(stdout)
p.kill()

问题:进程需终止才能获取输出,还存在编码错误问题;尝试p.stdout、subprocess.run均未解决。此外,coproc未安装且无法安装。

提问

请问与该Python进程进行输入输出交互的正确方法是什么?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 13:25:18