从Python程序向命令行提示符发送输入

时间:2015-01-19 19:49:48

标签: python starcluster

我认为这是一个非常简单的问题,但我一直没有找到一个简单的答案。

我正在运行一个终止AWS集群的python程序(使用starcluster)。我只是使用子进程从我的python程序调用一个命令,如下所示。

subprocess.call('starcluster terminate cluster', shell=True)

实际命令与我的问题基本无关,但提供了一些背景信息。此命令将开始终止群集,但会在继续之前提示输入是/否输入,如下所示:

Terminate EBS cluster (y/n)? 

如何在我的python程序中自动输入yes作为此提示的输入?

3 个答案:

答案 0 :(得分:5)

虽然possible to do with subprocess alone in somewhat limited way,但我会选择pexpect进行此类互动,例如:

import pexpect
child = pexpect.spawn('starcluster terminate cluster')
child.expect('Terminate EBS cluster (y/n)?')
child.sendline('y')

答案 1 :(得分:2)

您可以使用Popen写入stdin:

from subprocess import Popen, PIPE
proc = Popen(['starcluster', 'terminate', 'cluster'], stdin=PIPE)
proc.stdin.write("y\r")

答案 2 :(得分:0)

检查目标程序的文档可能最简单。通常可以将标志设置为对所有提示回答“是”,例如apt-get -y install