【问题标题】:read the output of a process while the process is running在进程运行时读取进程的输出
【发布时间】:2013-01-25 23:15:50
【问题描述】:

我需要启动一个进程并在进程运行时读取该进程的输出。我希望能够打印输出(可选)并在过程完成后返回输出。这是我到目前为止的内容(从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。

【问题讨论】:

  • 在我的 Linux 3.2 上运行良好,并且不关闭已关闭的 fd 似乎是一个非常不可能的错误。当您strace Python 程序时,您看到了什么?另外,您能否包含您正在使用的command 的值?
  • 感谢您的评论!问题实际上是命令,它是一个“svn export ...”,svn 进程希望用户第一次输入(登录名、密码)。对不起……

标签: python linux python-3.x subprocess popen


【解决方案1】:

文档说

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.

我知道我以前在 Windows 上遇到过问题。

我认为该命令不知何故在无缓冲模式下运行。

文档中有使用 subprocess 的方法,您的声音类似于 shell-backquote,但您对 subprocess 的使用是不同的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 2016-08-20
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多