此问题在 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, subprocess
f = open("a.txt", "w")
subprocess.Popen(["cmd"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
f.close()
os.remove(f.name)
Traceback(最近一次调用最后一次):
文件“stdin”,第 1 行,在模块中
WindowsError: [Error 32] Le processus ne peut pas accÚder au
fichier car ce fichier est utilisÚ par un autre processus: 'a.txt'
现在修复:
import os, subprocess
f = 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)
工作。
希望对我有所帮助