142*_*424 11 python windows handle multiprocessing
在Windows上使用多处理,似乎任何打开的文件句柄都由生成的进程继承.这具有锁定它们的令人不快的副作用.
我对以下任一方面感兴趣:
1)防止继承
2)从生成的进程中释放文件的方法
考虑以下代码在OSX上工作正常,但在os.rename上的窗口崩溃
from multiprocessing import Process
import os
kFileA = "a.txt"
kFileB = "b.txt"
def emptyProcess():
while 1:
pass
def main():
# Open a file and write a message
testFile = open(kFileA, 'a')
testFile.write("Message One\n")
# Spawn a process
p = Process(target=emptyProcess)
p.start()
# Close the file
testFile.close()
# This will crash
# WindowsError: [Error 32] The process cannot access the file
# because it is being used by another process
os.rename(kFileA, kFileB)
testFile = open(kFileA, 'a')
testFile.write("Message Two\n")
testFile.close()
p.terminate()
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
该fileno()方法返回由运行时库分配的文件编号。给定文件编号,然后您可以调用msvcrt.get_osfhandle()以获取 Win32 文件句柄。在对 的调用中使用此句柄SetHandleInformation。因此,类似以下内容可能有效:
win32api.SetHandleInformation(
msvcrt.get_osfhandle(testFile.fileno()),
win32api.HANDLE_FLAG_INHERIT,
0)
Run Code Online (Sandbox Code Playgroud)
我不确定该win32api模块的确切用法,但这应该有助于弥合 Python 文件对象和 Win32 句柄之间的差距。