[Python-Dev] tempfile.TemporaryFile on Windows NT

Tim Peters tim.peters at gmail.com
Wed Sep 15 20:51:16 CEST 2004


[Martin v. Löwis]
> The tempfile module has a wrapper class to implement
> delete on close. On NT+, this is not necessary, since
> the system supports the O_TEMPORARY flag. However
> the wrapper is still created 'so that file.name is useful
> (i.e. not "(fdopen)"'. I find this a weak argument, since
> file.name is also "fdopen" on POSIX.

File names are much more important on Windows, because Windows doesn't
allow to rename or delete an open file, two things Unixheads are
apparently incapable of avoiding.  Without a name, debugging Unixhead
code on Windows gets harder.  Files on Windows, at least from the std
C level, always have names.

> So I would like to drop the wrapper object on Windows NT,
> and have tempfile.TemporaryFile return a proper file
> object. Any objections?

I would sorely miss knowing the name.
 
> If there are objections, would they change if file.name
> would point uniformly to the file name of the temporary
> file?

Yes, but file.name is read-only now -- you can't change file.name from
Python code.

> If so, should this be better achieved by os.fdopen grow
> a name argument, or by using builtin open() in the first
> place? On Windows, one can pass the additional "D" flag
> to open() to get a delete-on-close file.

The latter doesn't fly, because there's no flag to open() that gets
the effect of the Windows O_NOINHERIT, and O_NOINHERIT is a pragmatic
necessity for sane use of temp files on Windows.  Indeed, although the
docs don't say this, without O_NOINHERIT even O_TEMPORARY isn't
reliable (program P creates a file F w/ O_TEMPORARY but not
O_NOINHERIT; P spawns program Q; Q inherits F's file descriptor, but
does *not* inherit the "delete on close" info about F; P exits; F is
not deleted then because a handle is still open on F (in Q); Q exits;
F isn't deleted then either because Q never knew that F was a "delete
on close" file; P and Q are both gone now, but F never goes away;
specifying O_NOINHERIT too stops this).

BTW, the docs also don't say this:  a file created with O_TEMPORARY
cannot be opened by name again, not even by the process that created
the file.  That's why there's no "security risk" in having a named
O_TEMPORARY file visible in the filesystem on Windows (although, as
above, that can lose if O_NOINHERIT isn't used too, or even if the
creating process goes away without running the C runtime cleanup
code).


More information about the Python-Dev mailing list