小编per*_*den的帖子

如何打印和显示subprocess stdout和stderr输出而不失真?

也许在以太中有人可以帮我解决这个问题.(我在SO上已经看到了很多类似的问题,但没有一个涉及标准输出和标准错误或处理与我相似的情况,因此这个新问题.)

我有一个python函数打开一个子进程,等待它完成,然后输出返回代码,以及标准输出和标准错误管道的内容.当进程正在运行时,我还想在填充它们时显示两个管道的输出.我的第一次尝试导致了这样的事情:

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

stdout = str()
stderr = str()
returnCode = None
while True:
    # collect return code and pipe info
    stdoutPiece = process.stdout.read()
    stdout = stdout + stdoutPiece
    stderrPiece = process.stderr.read()
    stderr = stderr + stderrPiece
    returnCode = process.poll()

    # check for the end of pipes and return code
    if stdoutPiece == '' and stderrPiece == '' and returnCode != None:
        return returnCode, stdout, stderr

    if stdoutPiece != '': print(stdoutPiece)
    if stderrPiece != '': print(stderrPiece) …
Run Code Online (Sandbox Code Playgroud)

python subprocess

8
推荐指数
1
解决办法
3472
查看次数

标签 统计

python ×1

subprocess ×1