Temporary but named file with BSDDB

Tim Pinkawa timpinkawa at gmail.com
Mon Jun 14 00:34:11 EDT 2010


On Sun, Jun 13, 2010 at 11:01 PM, Jason <jason.heeris at gmail.com> wrote:
> I'd like to use the BSDDB module in an app (intended only for GNU/
> Linux like OSes).
>
> I don't need the on-disk file to hang around after I've used it. So as
> per the docs I gave it "None" for the filename.
>
> The problem is, it creates the temporary file in /var/tmp. If the user
> uses separate root and home partitions, the root partition is usually
> significantly smaller, and the file created will fill up the partition
> pretty quickly. Besides which, I'd rather have the file placed in the
> app's own working area under the user's home dir.
>
> I'm aware that I can pass in a path of my choosing to use for the DB.
> But then I'm at the other extreme of resource management — I need to
> clean it up myself, making sure there's no path out of the code that
> results in the file getting left behind, including exceptions or
> signals.
>
> Is there an in-between way to use the BSDDB module, where I can name
> the file I want to use but tell the module it's temporary so that it
> can be removed without my intervention?
>
> - Jason

http://docs.python.org/library/tempfile.html

The tempfile.TemporaryFile class should do the job. This part is
probably of particular interest to you:

"It will be destroyed as soon as it is closed (including an implicit
close when the object is garbage collected)."

Short of the interpreter itself crashing (exceedingly rare in my
experience), the file will be deleted regardless if your program exits
normally or as the result of an exception.

As for the location of the file:

"If dir is specified, the file will be created in that directory;
otherwise, a default directory is used. The default directory is
chosen from a platform-dependent list, but the user of the application
can control the directory location by setting the TMPDIR, TEMP or TMP
environment variables."

My guess is it would end up in /tmp by default, unless your system is
configured otherwise.

Hope this helps,
Tim



More information about the Python-list mailing list