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

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

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

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

实际命令在很大程度上与我的问题无关,但提供了一些背景信息.此命令将开始终止集群,但在继续之前将提示输入yes / no,如下所示:

Terminate EBS cluster (y/n)? 

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

最佳答案 你可以使用Popen写入stdin:

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