gpt4 book ai didi

python 子进程: check to see if the executed script is asking for user input

转载 作者:太空狗 更新时间:2023-10-30 01:27:58 25 4
gpt4 key购买 nike

import subprocess

child = subprocess.Popen(['python', 'simple.py'], stdin=subprocess.PIPE)
child.communicate('Alice')

我知道你可以通过 communicate 与执行的脚本进行通信您如何检查脚本“simple.py”是否要求用户输入?

simple.py 可能需要 5-10 个用户输入,因此简单地硬编码 communicate 是不够的。

[编辑]:想要在脚本运行时解析标准输出并与脚本通信

while True:
if child.get_stdout() == '?':
# send user input

最佳答案

一个简单的例子:

简单的.py:

i = raw_input("what is your name\n")
print(i)
j = raw_input("What is your age\n")
print(j)

读写:

import subprocess

child = subprocess.Popen(['python2', 'simple.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

for line in iter(child.stdout.readline, ""):
print(line)
if "name" in line:
child.stdin.write("foo\n")
elif "age" in line:
child.stdin.write("100\n")

输出:

what is your name

foo

What is your age

100

关于 python 子进程: check to see if the executed script is asking for user input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35751295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com