[英]How to automatically input using python Popen and return control to command line
我有一個關於subprocess.Popen的問題。我正在調用一個shell腳本並提供很少的輸入。 幾次輸入后,我希望用戶運行python腳本輸入。
是否可以將控制從Popen進程轉移到命令行。
我添加了示例腳本
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的輸出
hi
hello a
Whats up b
Tell something else
請建議是否有其他方法可以解決此問題
一旦您的最后一次write
在您的python腳本中執行,它將退出,並且子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
許多人可能會對此感到畏縮,以此為出發點。 正如其他人所指出的那樣,stdin / stdout交互可能會對子進程產生挑戰,因此請繼續研究。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.