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

如何操作:close_fds = True并在Windows上重定向stdout / stderr

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

如何操作:close_fds = True并在Windows上重定向stdout / stderr

默认情况下,此问题已在Python 3.7+上修复

这绝对是一个棘手的技巧:答案是在使用

subprocess
模块之前迭代已打开的文件描述符。

def _hack_windows_subprocess():    """HACK: python 2.7 file descriptors.    This magic hack fixes https://bugs.python.org/issue19575    by adding HANDLE_FLAG_INHERIT to all already opened file descriptors.    """    # See https://github.com/secdev/scapy/issues/1136    import stat    from ctypes import windll, wintypes    from msvcrt import get_osfhandle    HANDLE_FLAG_INHERIT = 0x00000001    for fd in range(100):        try: s = os.fstat(fd)        except: continue        if stat.S_ISREG(s.st_mode): handle = wintypes.HANDLE(get_osfhandle(fd)) mask   = wintypes.DWORd(HANDLE_FLAG_INHERIT) flags  = wintypes.DWORd(0) windll.kernel32.SetHandleInformation(handle, mask, flags)

这是一个没有它就会崩溃的示例:

import os, subprocessf = open("a.txt", "w")subprocess.Popen(["cmd"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)f.close()os.remove(f.name)

追溯(最近一次通话):

文件“ stdin”,第1行,在模块中

WindowsError:[错误32]自动处理程序,自动处理程序:’a.txt’

现在修复:

import os, subprocessf = open("a.txt", "w")_hack_windows_subprocess()subprocess.Popen(["cmd"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)f.close()os.remove(f.name)

作品。

希望我有所帮助



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

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

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