Windows process ownership trouble

Tim Golden mail at
Thu Jun 26 19:44:38 CEST 2008

geoffbache wrote:
> Tim,
> Unfortunately my previous message was premature, it seems your
> workaround doesn't work
> either on my system (Windows XP, Python 2.5.1) I get the following
> printed out
> Traceback (most recent call last):
>   File "C:\TextTest\", line 12, in <module>
>     os.remove ("filename")
> WindowsError: [Error 32] The process cannot access the file because it
> is being used by another process: 'filename'
> close failed: [Errno 9] Bad file descriptor

(Assuming you have the pywin32 extensions installed...)

If you tweak your copy of by switching on
the use of the pywin32 extensions in preference to the
_subprocess module, the problem goes away, I think
because the PyHANDLE object auto-closes. I'm not saying
it won't ever fail -- the interactions of objects, scope,
frames, exceptions and garbage collection are things I've
never looked at too closely. But if you change line 378 from
if 0: to if 1:, then the following works fine:

import os
import subprocess

f = open ("filename", "w")
  p = subprocess.Popen ("blah", stdout=f)
except WindowsError:
  f.close ()

os.remove ("filename")


Note that the os.remove is *outside* the except handler.
This is, I think, because the underlying handle object
is still active until the try/except block closes. At which
point it is, probably, gc-ed and closes. And you can
remove the file.


More information about the Python-list mailing list