如何使用python Popen自动输入并将控制返回到命令行 [英] How to automatically input using python Popen and return control to command line

查看:66
本文介绍了如何使用python Popen自动输入并将控制返回到命令行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a question regarding subprocess.Popen .I'm calling a shell script and provide fewinputs. After few inputs ,I want user running the python script to input.

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

Is it possible to transfer control from Popen process to command line.

我添加了示例脚本

sample.sh

sample.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

test.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的输出

Output of the program python test.py

hi
hello a
Whats up b
Tell something else

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

Please suggest if any alternate methods available to solve this

推荐答案

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

As soon as your last write is executed in your python script, it will exit, and the child shell script will be terminated with it. You request seems to indicate that you would want your child shell script to keep running and keep getting input from the user. If that's the case, then subprocess might not be the right choice, at least not in this way. On the other hand, if having the python wrapper still running and feeding the input to the shell script is enough, then you can look at something like this:

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

许多人对此表示畏惧,以此为起点.正如其他人指出的那样,stdin/stdout交互对于子流程可能具有挑战性,因此请继续进行研究.

As many might cringe at this, take it as a starting point. As others have pointed out, stdin/stdout interaction can be challenging with subprocesses, so keep researching.

这篇关于如何使用python Popen自动输入并将控制返回到命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆