【问题标题】:Unable to answer yes to prompt using python subprocess无法回答是提示使用 python 子进程
【发布时间】:2019-10-28 11:40:46
【问题描述】:

我一直在尝试让一个子进程在 python 中运行,这需要我回答一个 y/N 提示。

我的代码如下:

      process = subprocess.Popen(
        [   
            "yes",
            "|",
            "mycommand",
            "launch"
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True
     )

当我尝试启动此 Popen 命令时,程序挂起。

当我在我的 Mac 终端中运行相同的命令时,它运行良好:

yes | mycommand launch

有什么方法可以默认yes?

【问题讨论】:

  • 您的系统有yes 命令吗? mycommand 是什么?
  • 通常,您只会使用shell=False 的子进程调用的参数列表(由于命令行中的管道,这甚至不是您的选择)。尝试使用第一个参数只是字符串"yes | mycommand launch"

标签: python bash terminal subprocess


【解决方案1】:

你可以使用bash -csh -c

#! /usr/bin/env python
import subprocess

def run_cmd(cmd):
    result = subprocess.run([
      '/bin/bash',
      '-c',
      cmd
    ], stdout=subprocess.PIPE)
    returncode = result.returncode
    stdout = result.stdout
    return { 'returncode' : returncode, 'stdout': stdout}


r = run_cmd('yes | head')
print(r)

输出:

{'returncode': 0, 'stdout': b'y\ny\ny\ny\ny\ny\ny\ny\ny\ny\n'}

如果要将标准输出打印为解码字符串:

print(r['stdout'].decode('utf-8'))

【讨论】:

    猜你喜欢
    • 2019-03-02
    • 2018-05-12
    • 2014-10-01
    • 1970-01-01
    • 2012-05-15
    • 2016-04-10
    • 2019-03-15
    • 1970-01-01
    相关资源
    最近更新 更多