在 Python 中使用 subprocess.Popen 检查进程状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14043030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:14:59  来源:igfitidea点击:

checking status of process with subprocess.Popen in Python

pythonmultiprocessing

提问by

If I invoke a process with subprocess.Popenin Python as follows:

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

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

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

what is the correct way to see its status? Not its output to stdout or stderr, but its exit status once it's finished (e.g. 0 for success or another for failure)?

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

采纳答案by BorrajaX

returncodeis indeed the answer, but the solution doesn't need to be complicated.

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

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

More info in the Python subprocessdocs.

Pythonsubprocess文档中的更多信息。

回答by BorrajaX

You may need to call a waiton your subprocess and then (once is done) check the status in the returncodefield of the subprocess instance.

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

I have a little routine that calls stuff, maybe it'll help...

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

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

You can try it with:

你可以试试:

print "This is the return: %s" % singleProcessExecuter(["ls", "-la"])

回答by Katriel

A process doesn't have a return code until it's finished executing. Therefore, if it hasn't yet finished, you have to decide what you want to do: wait for it, or return some indicator of "I haven't finished yet".

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

If you want to wait, use communicateand then check the returncodeattribute.

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

If you want to check whether the return code is set, and return Noneif not, use Popen.poll().

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

Popen.poll()

Check if child process has terminated. Set and return returncode attribute.

民意调查()

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

(if process hasn't terminated, poll()returns None)

(如果进程尚未终止,则poll()返回None