Reputation: 2737
I'm currious as to know if the behavior of with with os.fork is defined somehow in the python specification and how I should use with with os.fork.
If I do, for example:
import tempfile
import os
with tempfile.TemporaryDirectory() as dir:
pid = os.fork()
print(pid)
print(dir)
Then it seems to be using the naive behavior of deleting the TemporaryDirectory twice:
> 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'
I'm wondering:
Upvotes: 1
Views: 373
Reputation: 2737
Not using with, and doing this the dirty old way works.
> 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
Upvotes: 1