如何在不失真的情况下打印和显示子进程stdout和stderr输出?

如何在不失真的情况下打印和显示子进程stdout和stderr输出?,第1张

如何在不失真的情况下打印和显示子进程stdout和stderr输出?

使用来使管道成为非阻塞状态

fcntl.fcntl
,并使用
select.select
来等待数据在任一管道中变为可用。例如:

# Helper function to add the O_NonBLOCK flag to a file descriptordef make_async(fd):    fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)# Helper function to read some data from a file descriptor, ignoring EAGAIN errorsdef read_async(fd):    try:        return fd.read()    except IOError, e:        if e.errno != errno.EAGAIN: raise e        else: return ''process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)make_async(process.stdout)make_async(process.stderr)stdout = str()stderr = str()returnCode = Nonewhile True:    # Wait for data to become available     select.select([process.stdout, process.stderr], [], [])    # Try reading some data from each    stdoutPiece = read_async(process.stdout)    stderrPiece = read_async(process.stderr)    if stdoutPiece:        print stdoutPiece,    if stderrPiece:        print stderrPiece,    stdout += stdoutPiece    stderr += stderrPiece    returnCode = process.poll()    if returnCode != None:        return (returnCode, stdout, stderr)

请注意,

fcntl
仅在包括Cygwin的类Unix平台上可用。

如果您需要它在不使用Cygwin的Windows上运行,那是可行的,但难度要大得多。您必须:

  • 使用pywin32库调用本机Win32 API
  • SetNamedPipeHandleState
    与with
    PIPE_NOWAIT
    一起使用以使stdout和stderr管道不阻塞
  • 使用
    WaitForMultipleObjects
    而不是
    select
    等待数据可用
  • 使用
    ReadFile
    读取数据


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5623825.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-15

发表评论

登录后才能评论

评论列表(0条)

    保存