如何 *** 作:close_fds = True并在Windows上重定向stdoutstderr

如何 *** 作:close_fds = True并在Windows上重定向stdoutstderr,第1张

如何 *** 作: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)

作品。

希望我有所帮助



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

原文地址: https://www.outofmemory.cn/zaji/5663080.html

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

发表评论

登录后才能评论

评论列表(0条)

保存