12

如果我在 Python 中调用一个进程,subprocess.Popen如下所示:

myproc = subprocess.Popen(...).communicate()

查看其状态的正确方法是什么?不是输出到标准输出或标准错误,而是完成后的退出状态(例如,0 表示成功或另一个表示失败)?

4

3 回答 3

24

returncode确实是答案,但解决方案不需要复杂。

process = subprocess.Popen(...)
stdoutdata, stderrdata = process.communicate()
print process.returncode

Pythonsubprocess文档中的更多信息。

于 2012-12-26T16:12:29.653 回答
10

进程在完成执行之前没有返回码。因此,如果它还没有完成,你必须决定你想要做什么:等待它,或者返回一些“我还没有完成”的指示符。

如果要等待,请使用communicate然后检查returncode属性。

如果要检查是否设置了返回码,None如果没有设置返回,使用Popen.poll().

Popen.poll()

检查子进程是否已终止。设置并返回 returncode 属性。

(如果进程没有终止,poll()返回None

于 2012-12-26T16:15:00.997 回答
1

您可能需要wait在子流程上调用 a ,然后(一旦完成)检查returncode子流程实例字段中的状态。

我有一个调用东西的小程序,也许它会有所帮助......

def singleProcessExecuter(command, ** kwargs):
    assert isinstance(command, list), "Expected 'command' parameter to be a list containing the process/arguments to execute. Got %s of type %s instead" % (command, type(command))
    assert len(command) > 0, "Received empty list of parameters"
    retval = {
            "exitCode": -1,
            "stderr": u"",
            "stdout": u"",
            "execTime": datetime.timedelta(0),
            "command": None,
            "pid": None
            }
    retval["command"] = command
    log.info("::singleProcessExecuter > At %s, executing \"%s\"" % (datetime.datetime.now(), " ".join(command)))
    #print("::singleProcessExecuter > At %s, executing \"%s\"" % (datetime.datetime.now(), " ".join(parameter)))
    cwd = kwargs.get("cwd", os.getcwd())
    user = kwargs.get("user", getUid())
    sheel = kwargs.get("shell", False)
    startDatetime = datetime.datetime.now()
    myPopy = subprocess.Popen(command, cwd=cwd, preexec_fn=os.seteuid(getUid(user)), shell=sheel, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    retval["pid"] = myPopy.pid
    log.debug("::singleProcessExecuter > Command \"%s\" got pid %s" % (" ".join(command), myPopy.pid))
    try:
        retval["stdout"], retval["stderr"] = myPopy.communicate()
        myPopy.wait()
    except OSError, osErr:
        log.debug("::singleProcessExecuter > Got %s %s in myPopy.communicate() when trying get output of command %s. It is probably a bug (more info: http://bugs.python.org/issue1731717)" % (osErr, type(osErr), command[0]))
    except Exception, e:
        log.warn("::singleProcessExecuter > Got %s %s when trying to get stdout/stderr outputs of %s" % (type(e), e, " ".join(command)))
        log.debug("::singleProcessExecuter > Got %s %s when trying to get stdout/stderr outputs of %s. Showing traceback:\n%s" % (type(e), e, " ".join(command), traceback.format_exc()))
        raise
    retval["exitCode"] = myPopy.returncode
    retval["execTime"] = datetime.datetime.now() - startDatetime
    #print(":singleProcessExecuter > This is %s's retval:\n%s" % (" ".join(parameter), retval)) 
    return retval

你可以试试:

print "This is the return: %s" % singleProcessExecuter(["ls", "-la"])
于 2012-12-26T16:08:14.490 回答