gpt4 book ai didi

python - 如何使用python Popen自动输入并将控制权返回到命令行

转载 作者:行者123 更新时间:2023-11-30 22:50:11 29 4
gpt4 key购买 nike

我有一个关于 subprocess.Popen 的问题。我正在调用 shell 脚本并提供一些输入。经过几次输入后,我希望用户运行 python 脚本来输入。

是否可以将控制从 Popen 进程转移到命令行。

我添加了示例脚本

样本.sh

echo "hi"
read input_var
echo "hello" $input_var
read input_var1
echo "Whats up" $input_var1
read input_var2
echo "Tell something else" $input_var2

测试.py

import os
from subprocess import Popen, PIPE

p=Popen([path to sample.sh],stdin=PIPE)
#sample.sh prints asks for input
p.stdin.write("a\n")
#Prompts for input
p.stdin.write("nothing much\n")
#After the above statement ,User should be able to prompt input
#Is it possible to transfer control from Popen to command line

程序 python test.py 的输出

hi
hello a
Whats up b
Tell something else

请建议是否有任何替代方法可以解决此问题

最佳答案

一旦在 python 脚本中执行了最后一个 write,它将退出,并且子 shell 脚本将随之终止。您的请求似乎表明您希望您的子 shell 脚本继续运行并继续从用户获取输入。如果是这样的话,那么 subprocess 可能不是正确的选择,至少不是这样。另一方面,如果 python 包装器仍在运行并将输入提供给 shell 脚本就足够了,那么您可以查看如下内容:

import os
from subprocess import Popen, PIPE

p=Popen(["./sample.sh"],stdin=PIPE)
#sample.sh prints asks for input
p.stdin.write("a\n")
#Prompts for input
p.stdin.write("nothing much\n")

# read a line from stdin of the python process
# and feed it into the subprocess stdin.
# repeat or loop as needed
line = raw_input()
p.stdin.write(line+'\n')
# p.stdin.flush() # maybe not needed

尽管许多人可能对此感到畏缩,但请以此为起点。正如其他人指出的那样,标准输入/标准输出交互对于子进程来说可能具有挑战性,因此请继续研究。

关于python - 如何使用python Popen自动输入并将控制权返回到命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39501950/

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