繁体   English   中英

Python-使用Popen.communicate()不能按预期捕获系统调用的stdout和stderr

[英]Python - Using Popen.communicate() does not capture the stdout and stderr of a system call as expected

我有一个执行系统调用的Python脚本(该调用实际上是一个java程序)。 我正在使用Popen.communicate() 尝试捕获stdoutstderr 但是,它仅适用于某些Java应用程序(我直接调用的所有java应用程序在外壳程序中直接执行时都会在屏幕上显示某些内容)。

我使用的代码如下:

    # Perform the java call
    try:

        p = subprocess.Popen(args,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)

    except OSError as e:
        error_msg = '  Error reading file while executing system command: {0}'.format(e.message)

    except ValueError as e:
        error_msg = '  Error in arugments while executing system command: {0}'.format(e.message)

    else:
        # Display the results in real time
        for line in iter(p.stdout.readline, ''):
            sys.stdout.write(line)

        # Grab the stdout and stderr from the process.
        output, err = p.communicate()

    finally:
        # Check to see if an internal error occurred. If not, flip the flag
        if not err and not error_msg:
            java_completed = True
        else:
            java_completed = False

在某些情况下,永远不会调用sys.stdout.write(line) ,而在其他情况下则不会调用。

有人对这个有经验么?

我注意到的第一件事是,您正在从流程标准输出中读取所有内容,然后尝试进行p.communicate() communicate :您已经从管道中读取了所有内容,因此p.communicate()output结果将始终为空。

但这不能解释为什么有时不调用sys.stdout.write

要记住的一件事是,有多种方法可以在控制台(即命令窗口)中显示内容。 打印到流程stdout流只是一种方法,这就是您可以使用以上代码捕获的方法。 如果我从Java时代回想起,有时会使用某种类型的Console类来显示到控制台,但这可能不使用stdout。 此外,高级控制台显示库(例如curses通常不写入stdout,它们直接与控制台对象交互。 我不知道如何或者是否可以从这些类型的过程中捕获输出,但是如果可能的话,它可能是非常特定于系统的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM