【问题标题】:Python: Popen.wait returns 1 even is the execution is successfulPython:即使执行成功,Popen.wait 也会返回 1
【发布时间】:2015-01-07 05:29:26
【问题描述】:

我有以下代码来执行命令并获取输出。

import os, sys, subprocess, string
def executeCommand(execstr):
    print "cmd: " + execstr
    p = subprocess.Popen(execstr, stdout=subprocess.PIPE, shell=True)
    output = ""
    (output, err) = p.communicate()
    p_status = p.wait()

    if (p_status != 0):
        print "Unable to execute "+ execstr

    return (string.strip(output))

cmd = "grep -R \"pattern\" sample.txt"
output = executeCommand(cmd)
print "output: "  +output

这里从 p.wait() 返回的 p_status 为 1(非零) 在命令行中执行命令时成功。 sample.txt 是一个空文本文件。 来自 p.communicate 的错误是无。 上面的代码有什么问题。

【问题讨论】:

  • 不相关:没有stderr=PIPE err总是 None。删除shell=True 并使用shlex.split(execstr)
  • 那么,要得到err,从p.communicate(),stderr=subprocess.PIPE,需要添加到Popen命令中吗?
  • 是的。它在文档中明确提及。

标签: python subprocess


【解决方案1】:

grep can return non-zero status even if there are no errors.

如果没有找到任何东西,它会返回1。出错时返回 2(或更大)。

【讨论】:

  • 谢谢!没有注意到 p.wait 返回子进程的退出代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-13
相关资源
最近更新 更多