【问题标题】:Python: Catching the output from subprocess.call with stdoutPython:使用标准输出捕获 subprocess.call 的输出
【发布时间】:2012-01-03 14:45:59
【问题描述】:

所以我试图保存我的subprocess.call 的输出,但我不断收到以下错误: AttributeError: 'int' object has no attribute 'communicate'

代码如下:

p2 = subprocess.call(['./test.out', 'new_file.mfj', 'delete1.out'], stdout = PIPE)
output = p2.communicate[0]

【问题讨论】:

  • 推荐 Popen 的答案在 2012 年被问到这个问题时基本上是正确的,但现代正确答案是使用 subprocess.runsubprocess.check_output 如果您需要一个简单的 API 和/或与旧 Python 版本的兼容性。 The subprocess documentation 在第一部分的第一段中说明了这一点; “调用子流程的推荐方法是对它可以处理的所有用例使用run() 函数。

标签: python


【解决方案1】:

你应该使用子进程

    try:            
        subprocess.check_output(['./test.out', 'new_file.mfj', 'delete1.out'], shell=True, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as exception:
        print exception.output

【讨论】:

    【解决方案2】:

    您正在寻找subprocess.Popen() 而不是call()

    您还需要将其更改为p2.communicate()[0]

    【讨论】:

    • 这在 2012 年是正确的,但现在推荐的解决方案是避免使用 Popen,除非您的用例需要它。
    【解决方案3】:

    那是因为 subprocess.call 返回一个 int:

    subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
    
        Run the command described by args. Wait for command to complete, then return the returncode attribute.
    

    看起来你想要subprocess.Popen().

    这是我必须这样做的一段典型代码:

    p = Popen(cmd, stdout=PIPE, stderr=PIPE, bufsize=256*1024*1024)
    output, errors = p.communicate()
    if p.returncode:
        raise Exception(errors)
    else:
        # Print stdout from cmd call
        print output
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      相关资源
      最近更新 更多