从 Python 程序向命令行提示符发送输入
Send input to command line prompt from Python program
我认为这是一个非常简单的问题,但我一直未能找到一个简单的答案。
我是运行一个终止AWS集群(使用starcluster)的python程序。我只是使用子进程从我的 python 程序调用命令,如下所示。
subprocess.call('starcluster terminate cluster', shell=True)
实际命令在很大程度上与我的问题无关,但提供了一些上下文。此命令将开始终止集群,但会在继续之前提示输入 yes/no,如下所示:
Terminate EBS cluster (y/n)?
如何从我的 python 程序中自动输入 yes 作为此提示的输入?
虽然possible to do with subprocess
alone in somewhat limited way, I would go with pexpect
这样的互动,例如:
import pexpect
child = pexpect.spawn('starcluster terminate cluster')
child.expect('Terminate EBS cluster (y/n)?')
child.sendline('y')
查看目标程序的文档可能是最简单的。通常可以设置一个标志以对所有提示回答是,例如 apt-get -y install
.
您可以使用 Popen 写入标准输入:
from subprocess import Popen, PIPE
proc = Popen(['starcluster', 'terminate', 'cluster'], stdin=PIPE)
proc.stdin.write("y\r")
我认为这是一个非常简单的问题,但我一直未能找到一个简单的答案。
我是运行一个终止AWS集群(使用starcluster)的python程序。我只是使用子进程从我的 python 程序调用命令,如下所示。
subprocess.call('starcluster terminate cluster', shell=True)
实际命令在很大程度上与我的问题无关,但提供了一些上下文。此命令将开始终止集群,但会在继续之前提示输入 yes/no,如下所示:
Terminate EBS cluster (y/n)?
如何从我的 python 程序中自动输入 yes 作为此提示的输入?
虽然possible to do with subprocess
alone in somewhat limited way, I would go with pexpect
这样的互动,例如:
import pexpect
child = pexpect.spawn('starcluster terminate cluster')
child.expect('Terminate EBS cluster (y/n)?')
child.sendline('y')
查看目标程序的文档可能是最简单的。通常可以设置一个标志以对所有提示回答是,例如 apt-get -y install
.
您可以使用 Popen 写入标准输入:
from subprocess import Popen, PIPE
proc = Popen(['starcluster', 'terminate', 'cluster'], stdin=PIPE)
proc.stdin.write("y\r")