On 7/06/2006 7:50 AM, Gregory Piñero wrote:
Hey group,
I have a command line tool that I want to be able to call from a
Python script. The problem is that this tool only writes to a file.
So my solution is to give the tool a temporary file to write to and
then have Python read that file. I figure that's the safest way to
deal with this sort of thing. (But I'm open to better methods).
Here's my code so far, could anyone tell me the proper way to use
tempfile. This code won't let the tool write to the file because
Python has it locked. But I'm worried that if I close the file then
windows might take it away? I have no idea.
Me neither, not having faced this situation before. To acquire an idea,
I'd Read The Fantastic Manual:
(my comments enclosed in [])
"""
TemporaryFile( [mode='w+b'[, bufsize=-1[, suffix[, prefix[, dir]]]]])
Return a file (or file-like) object that can be used as a temporary
storage area. The file is created using mkstemp. It will be destroyed as
soon as it is closed (including an implicit close when the object is
garbage collected).[That seems to answer one question] Under Unix, the
directory entry for the file is removed immediately after the file is
created. Other platforms do not support this; your code should not rely
on a temporary file created using this function having or not having a
visible name in the file system.
The mode parameter defaults to 'w+b' so that the file created can be
read and written without being closed. Binary mode is used so that it
behaves consistently on all platforms without regard for the data that
is stored. bufsize defaults to -1, meaning that the operating system
default is used.
The dir, prefix and suffix parameters are passed to mkstemp().
NamedTemporaryFile( [mode='w+b'[, bufsize=-1[, suffix[, prefix[, dir]]]]])
This function operates exactly as TemporaryFile() does, except that the
file is guaranteed to have a visible name in the file system (on Unix,
the directory entry is not unlinked). That name can be retrieved from
the name member of the file object. Whether the name can be used to open
the file a second time, while the named temporary file is still open,
varies across platforms (it can be so used on Unix; it cannot on Windows
NT or later [That seems to answer the other question]). New in version 2.3.
"""
So I'd be thinking about using the (deprecated) mktemp() instead,
perhaps trying to cut down the chance of conflicts by (a) using a prefix
e.g. "pdf2txttmp" and/or (b) using a dir of "." -- then asking the
cognoscenti what are the drawbacks of this approach.
HTH,
John