1

我需要启动一个进程并在进程运行时读取该进程的输出。我希望能够打印输出(可选)并在过程完成后返回输出。这是我到目前为止所拥有的(从stackoverflow中的其他答案合并):

def call(command, print_output):
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out = ""

    while True:
        line = process.stdout.readline().rstrip().decode("utf-8")
        if line == '':
            break

        if print_output:
            print(line)

        out += line + "\n"

    process.wait()

    return process.returncode, out

此代码在 Windows 中运行良好(使用 Windows 7、python 3.3 测试)但在 linux(Ubuntu 12.04、python 3.2)中失败。在linux中,脚本挂在行

line = process.stdout.readline().rstrip().decode("utf-8")

当该过程完成时。

代码有什么问题?我也尝试使用 process.poll() 检查进程是否已完成,但在 Linux 下总是返回 None 。

4

1 回答 1

0

The docs say

Warning Use communicate() rather than 
.stdin.write, .stdout.read or .stderr.read to
avoid deadlocks due to any of the other OS pipe buffers filling 
up and blocking the child process.

I know I had issues before on Windows.

I presume the command is running in unbuffered mode somehow.

The docs have recipes for using subprocess your sounds like shell-backquote yet your use of subprocess is different.

于 2013-02-10T20:53:10.217 回答