【问题标题】:How can I programmatically write expected input on terminal command?如何以编程方式在终端命令上写入预期输入?
【发布时间】:2020-01-09 17:35:44
【问题描述】:

我正在尝试使用 python 2.7 以编程方式执行此命令:

aws configure --profile name_profile

问题是this command一执行就要求用户输入一些参数:

$ aws configure
AWS Access Key ID [****]: access_key_input
AWS Secret Access Key [****]: secret__key_input
Default region name [us-west-1]: region_optional_input

我知道如何在 python 中执行命令,通常这些行你就完成了:

def execute_command(command):
    try:
        process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output, error = process.communicate()
        return output, error
    except Exception as error:
        return None, error

但是在这种情况下,我不知道如何模拟这个过程。我想写类似的东西

def add_profile(access_key, access_secret, name_profile, region=None)

那应该执行之前的命令并用参数回答问题。

在此先感谢大家。

【问题讨论】:

  • 所以您想询问用户输入,然后使用它来配置您的 aws 连接?
  • @MasonCaiby 不,这个命令需要自动化一些其他的东西,想法是用户不需要输入任何东西,我会从数据库中获取所有数据,这个过程会在后端执行,不涉及任何前端。
  • 您是否要进行大量的 aws 配置?问题是您正在尝试使用 python 脚本中的命令行工具...为什么要创建这么多配置文件?您可以使用stdout 将access_key 和\n 发送到cli 工具吗?

标签: python subprocess aws-cli


【解决方案1】:

这个问题与 AWS CLI 的关系比与 Python 的关系更大。配置AWS credentials 的简单、非交互方式是使用AWS shared credentials file。

不必与命令行交互,您可以让您的函数创建这样一个共享凭证文件,并确保在完成后清理或删除该文件。

如果您坚持使用 Python 与 AWS CLI 进行交互,则有几种方法。通过快速的 Google 搜索,我找到了this SO post。根据我自己使用 Python 以编程方式与命令行交互的经验,我使用了 Pexpect。这个库基本上让您预期某些文本将出现在 CLI 中,之后您的程序可以将新数据输出到 CLI。

【讨论】:

    【解决方案2】:

    尽管使用 Pexpect(感谢 @natn2323)解决了问题,但我发现如果您不需要检查动态问题并且问题的数量和类型始终相同。这也可以:

    try:
        process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
        output, error = process.communicate(input=b"answer1\nanswer2\n\n")
        return output, error
    except Exception as error:
        return None, error
    

    请注意,对于我的案例(aws configure),最后 2 个答案(输入“\n\n”的最后一部分)是空的。

    我在使用 Pycharm 和使用 Pexpect 时遇到了一些错误,所以最后我将使用这个解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-01
      • 2015-07-30
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 2016-04-03
      相关资源
      最近更新 更多