【问题标题】:How to automatically input using python Popen and return control to command line如何使用python Popen自动输入并将控制权返回到命令行
【发布时间】:2017-01-22 22:32:33
【问题描述】:

我有一个关于 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

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

【问题讨论】:

  • 为什么不起作用?你能再解释一下这个问题吗?
  • 在上面的程序中,我运行了test.py。 input_var2 应该由用户输入。但它没有发生。输出只是“告诉其他事情”。我错过了什么吗?
  • @John1024 尝试了上述建议。结果相同。谢谢。
  • 谢谢@John1024 正如你所指出的,最初提供了p=Popen([path to sample.sh],stdin=PIPE)。后来我尝试了p=Popen(["./sample.sh"],stdin=PIPE)。我没有看到任何错误消息。我将前两个变量从python传递到shell脚本,并期望从用户输入第三个变量。但是代码不要求第三个变量。我是无法附上截图。我正在从 putty ssh 会话运行这个程序。
  • @John1024 是的,如果在没有正确路径的情况下给出sample.sh,你是对的。我曾经得到NameError 错误。我已经更正了这个问题。在更正test.py 之后或在实际运行它之后引号内的目录./sample.sh,我遇到了上述问题。如果有人之前遇到过这个问题,请指导。

标签: python shell command-line


【解决方案1】:

一旦你的最后一个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 交互对于子流程可能具有挑战性,因此请继续研究。

【讨论】:

  • (1) 在我看来,这可以解决 OP 的问题:+1。 (2) 可能应该在代码末尾添加 p.wait() 以避免,如果 python 要终止 before 脚本,创建一个僵尸。 (3) 此外,为了更笼统,raw_input... 如您所知,可以放在一个循环中。
  • 谢谢@sal。它起作用了。我将阅读有关 stdin/stdout 交互子流程的信息。
猜你喜欢
  • 2016-09-02
  • 2013-04-08
  • 2011-12-11
  • 1970-01-01
  • 2014-09-07
  • 2017-11-20
  • 1970-01-01
  • 2013-01-04
  • 1970-01-01
相关资源
最近更新 更多