我很高兴知道是否在python规范中以某种方式定义了与os.fork一起使用的行为以及我应该如何使用os.fork。
如果我这样做,例如:
import tempfile
import os
with tempfile.TemporaryDirectory() as dir:
pid = os.fork()
print(pid)
print(dir)
然后它似乎使用了两次删除TemporaryDirectory的天真行为:
> python3 foo.py
27023
/tmp/tmpg1typbde
0
/tmp/tmpg1typbde
Traceback (most recent call last):
File "foo.py", line 6, in <module>
print(dir)
File "/usr/lib/python3.4/tempfile.py", line 824, in __exit__
self.cleanup()
File "/usr/lib/python3.4/tempfile.py", line 828, in cleanup
_rmtree(self.name)
File "/usr/lib/python3.4/shutil.py", line 467, in rmtree
onerror(os.rmdir, path, sys.exc_info())
File "/usr/lib/python3.4/shutil.py", line 465, in rmtree
os.rmdir(path)
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpg1typbde'
我想知道:
答案 0 :(得分:1)
不使用,并且以旧的方式运行。
> cat foo.py
import tempfile
import os
import shutil
temp_dir = tempfile.mkdtemp(prefix="foo")
pid = os.fork()
print(pid)
print(temp_dir)
if not pid:
input("pid: %s\nPress enter to continue."%pid)
if pid:
print("pid: %s\nWaiting for other pid to exit."%pid)
os.waitpid(pid,0)
shutil.rmtree(temp_dir)
print("Bye")
> python3 foo.py
27510
/tmp/foopyvuuwjw
pid: 27510
Waiting for other pid to exit.
0
/tmp/foopyvuuwjw
pid: 0
Press enter to continue.
Bye