在 Windows 上使用多处理似乎任何打开的文件句柄都由衍生的进程继承。这具有锁定它们的令人不快的副作用。
我对以下任一感兴趣:
1)防止继承
2)从生成的进程中释放文件的方法
考虑以下代码,它在 OSX 上运行良好,但在 os.rename 的 Windows 上崩溃
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()