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

2024-06-16 12:28:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

实际的命令与我的问题基本无关,但提供了一些上下文。此命令将开始终止群集,但在继续之前将提示输入yes/no,如下所示:

^{pr2}$

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


Tags: 答案命令程序awstrue进程集群shell
3条回答

检查目标程序的文档可能是最简单的方法。通常可以设置一个标志来对所有提示回答yes,例如apt-get -y install。在

您可以使用Popen向stdin写入:

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

possible to do with ^{} alone in somewhat limited way时,我将使用^{}进行此类交互,例如:

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

相关问题 更多 >