栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在不失真的情况下打印和显示子进程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
    读取数据


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/617741.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号