开发者

python: can't delete open file from os.execl'd python script on windows

开发者 https://www.devze.com 2023-02-10 13:28 出处:网络
Consider delfoo.py and its partner, lol.py: #----delfoo.py----- import os os.unlink(\"foo.txt\") #----lol.py----

Consider delfoo.py and its partner, lol.py:

#----delfoo.py-----
import os
os.unlink("foo.txt")

#----lol.py----
import os,sys

f = open("foo.txt","w")
f.write("HI")
#not closing f on purpose!
os.execl(sys.executable, sy开发者_如何学Cs.executable, "delfoo.py")
print "If this line shows, then something is broken."

Invoking python lol.py yields (note the last line did not print):

C:\tmp>python lol.py

C:\tmp>Traceback (most recent call last):
  File "delfoo.py", line 2, in <module>
    os.unlink("foo.txt")
WindowsError: [Error 32] The process cannot access the file because it is being
used by another process: 'foo.txt'

I find this weird, since os.excel is supposed to replace the currently running process with another one. If it is replaced, and if after a program terminates one can delete the file even if it wasn't closed:

C:\tmp>del foo.txt

C:\tmp>dir foo.txt
 Volume in drive C has no label.
 Volume Serial Number is 1060-E78D

 Directory of C:\tmp

File Not Found

then why can't I delete the file from the new process that has replaced the previous one? How can I make it so the os.execld instance, delfoo.py, can unlink the file opened by its progenitor, lol.py, without closing said file?


You forgot to close the file handler:

#----lol.py----
import os,sys

f = open("foo.txt","w")
f.write("HI")
f.close() # HERE !
os.execl(sys.executable, sys.executable, "delfoo.py")


Just checking the os.execl*() gave me this:

The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered on these open files, you should flush them using sys.stdout.flush() or os.fsync() before calling an exec*() function.

I am guessing, along with not flushing the file objects, they are not closed as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消