在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()
如何從使用open()創建的文件獲取文件句柄,而不是os.open()? – 14256424 2009-06-04 17:54:45