python - 进程终止后Popen对象的returncode为None

标签 python subprocess

我正在使用 Popen 运行一个进程。我需要等待进程终止。我正在检查进程是否已通过 returncode 终止。当 returncode 不同于 None 时,进程必须终止。问题是,当 print_outputFalse 时,returncode 始终为 None,即使进程已完成运行(终止)。然而,当 print_outputTrue 时,情况并非如此。我正在使用以下代码来运行该过程:

def run(command, print_output=True):
    # code mostly from: http://sharats.me/the-ever-useful-and-neat-subprocess-module.html
    from subprocess import Popen, PIPE
    from threading import Thread
    from queue import Queue, Empty
    from time import sleep

    io_q = Queue()

    def stream_watcher(identifier, stream):
        for line in stream:
            io_q.put((identifier, line))

        if not stream.closed:
            stream.close()

    with Popen(command, stdout=PIPE, stderr=PIPE, universal_newlines=True) as proc:
        if print_output:

            Thread(target=stream_watcher, name='stdout-watcher', args=('STDOUT', proc.stdout)).start()
            Thread(target=stream_watcher, name='stderr-watcher', args=('STDERR', proc.stderr)).start()

            def printer():
                while True:
                    try:
                        # Block for 1 second.
                        item = io_q.get(True, 1)
                    except Empty:
                        # No output in either streams for a second. Are we done?
                        if proc.poll() is not None:
                            break
                    else:
                        identifier, line = item
                        print(identifier + ':', line, end='')

            Thread(target=printer, name='printer').start()

        while proc.returncode is None:
            sleep(2)
            proc.poll()

        if not proc.returncode == 0:
            raise RuntimeError(
                'The process call "{}" returned with code {}. The return code is not 0, thus an error '
                'occurred.'.format(list(command), proc.returncode))

        return proc.stdout, proc.stderr

任何可能导致此问题的线索?

编辑:发现了一些很奇怪的东西。我正在运行以下代码:

run(my_command, True)
print('--------done--------')
run(my_command, False)
print('--------done--------')
即使 run(my_command, False) 被执行,

'--------done--------' 也不会被打印出来。

最佳答案

长话短说

subprocess.Popen()之后添加popen.wait()

解释部分(某种)

Python运行速度太快,子进程结束但无法读取返回码

(我真的不知道为什么会这样。欢迎解释)

我为什么要用这个:

Shell 命令执行并获取两者 返回码和输出(stdout)

def exec_cmd(cmd):
    pop = subprocess.Popen(shlex.split(cmd), stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
    pop.wait()
    return [pop.returncode, pop.communicate()[0]]

此外:请阅读 popen page 上的 .wait 警告

关于python - 进程终止后Popen对象的returncode为None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37942022/

相关文章:

python - subprocess.Popen 与 CLI 提示符交互

Python子进程问题

python - 有没有一个Python函数可以完成R中mapply的功能

python - 如何从 PyTorch 模型的特定层获取输出?

python - 自动对 pandas 数据框中具有相似名称的多个列进行分组

python - 带双引号的子流程

Python 弹出命令。等到命令完成

python + linux + 不终止子进程问题

python - 提取嵌入在python中的字符串中的多个列表