473,663 Members | 2,933 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

tempfile Question

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.

<code>
PDFTOTEXTPATH=r 'C:\xpdf-3.01pl2-win32\xpdf-3.01pl2-win32\pdftotext .exe'

def read_pdf_text(f ilepath):
outfile=tempfil e.NamedTemporar yFile()
outfilename=out file.name
command=r'"%s" "%s" "%s"' % (PDFTOTEXTPATH, filepath,outfil ename)
result=os.popen (command).read( )
pdftext=outfile .read()
outfile.close()
return pdftext
</code>

Much thanks!

--
Gregory Piñero
Chief Innovation Officer
Blended Technologies
(www.blendedtechnologies.com)
Jun 6 '06 #1
5 1701
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().
NamedTemporaryF ile( [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
Jun 6 '06 #2
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.


Another Fantastic Manual gives another idea:
"""
Pdftotext reads the PDF file, PDF-file, and writes a text
file, text-file. If text-file is not specified, pdftotext
converts file.pdf to file.txt. If text-file is '-', the
text is sent to stdout.
"""

Why not try reading back the child process's stdout? I would have
thought there would be no shortage of examples and help for this idea ...

Cheers,
John
Jun 7 '06 #3
On 7/06/2006 3:57 PM, Dennis Lee Bieber wrote:
On Wed, 07 Jun 2006 09:56:13 +1000, John Machin <sj******@lexic on.net>
declaimed the following in comp.lang.pytho n:
The dir, prefix and suffix parameters are passed to mkstemp().

<snip>
So I'd be thinking about using the (deprecated) mktemp() instead,


I think you passed over the mkstemp() variation. Granted, it, too,
returns an opened file, along with the full pathname of the file, but it
requires the caller to handle eventual disposal of the file.

Merely close the opened file; pass the pathname to the subprocess,
await completion of subprocess, reopen the file for use in Python...
Then at the end, close the file and use the pathname to delete the file
from the system.


I passed over mkstemp() because (according to my reading of the manual),
mkstemp() requires an *extra* step (close the file), leaving the
situation then *exactly* the same as with mktemp() i.e. some pirate
process may molest the file before the caller's child process can open
the file.

Cheers,
John
Jun 7 '06 #4
John Machin wrote:
On 7/06/2006 3:57 PM, Dennis Lee Bieber wrote:
On Wed, 07 Jun 2006 09:56:13 +1000, John Machin <sj******@lexic on.net>
declaimed the following in comp.lang.pytho n:

The dir, prefix and suffix parameters are passed to mkstemp().


<snip>
So I'd be thinking about using the (deprecated) mktemp() instead,


I think you passed over the mkstemp() variation. Granted, it, too,
returns an opened file, along with the full pathname of the file, but it
requires the caller to handle eventual disposal of the file.

Merely close the opened file; pass the pathname to the subprocess,
await completion of subprocess, reopen the file for use in Python...
Then at the end, close the file and use the pathname to delete the file
from the system.

I passed over mkstemp() because (according to my reading of the manual),
mkstemp() requires an *extra* step (close the file), leaving the
situation then *exactly* the same as with mktemp() i.e. some pirate
process may molest the file before the caller's child process can open
the file.

Surely if you set permissions correctly on /tmp (sticky-but to require
ownership for deletion) and you create your temporary file with sensible
ownership and permissions then rogue processes without root privileges
can't do anything bad to your files. Or am I wrong?

Of course if a rogue process has root privileges then all security bets
are off anyway.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Love me, love my blog http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Jun 7 '06 #5
On 8/06/2006 2:57 AM, Dennis Lee Bieber wrote:
On Wed, 07 Jun 2006 21:53:02 +1000, John Machin <sj******@lexic on.net>
declaimed the following in comp.lang.pytho n:
I passed over mkstemp() because (according to my reading of the manual),
mkstemp() requires an *extra* step (close the file), leaving the
situation then *exactly* the same as with mktemp() i.e. some pirate
process may molest the file before the caller's child process can open
the file.

mktemp() creates ONLY the file name, but not the file itself. This
means another process calling mktemp() has the possibility of generating
the SAME file name before the first opens/creates the named file.


Thanks, Dennis. You are quite correct. I'm a dill: I read """Return an
absolute pathname of a file that did not exist at the time the call is
made""" as implying that the file existed after the call, brushed aside
my brief wonderment about what was deprecable about all that, and didn't
even try it at the interactive prompt.

Cheers,
John
Jun 7 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3816
by: Pierre Rouleau | last post by:
Hi all! I am using Python 2.3.1 on Win32 (NT, 2000). Whenever a file imports the standard tempfile module, Python 2.3.1 issues the following warning: C:\Python23\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is Deprecated; please use fcntl DeprecationWarning).
3
2848
by: Thomas Guettler | last post by:
Hi! Is there a need for the "@" in the filenames created with tempfile.mktemp()? I think it would be better to use only characters which are "shell save". At least with bash you need to quote the "@". Copy&past of the filename does not work.
2
4082
by: marco | last post by:
Hello, I having a problem creating directories with Python 2.3.4 (compiled with gcc 3.2.2, under Linux 2.4.20-31.9). I'm writing a plugin which works in the following way: GUI -- talks to --> Perl backend Perl backend -- talks to --> Python plugin Python plugin -- talks to --> Python script
1
3098
by: Matt Garman | last post by:
I've been working on a curses-based application in Python. My application effectively has a series of screens (or windows). When one screen closes, the previous screen should be exactly redrawin in its original state (i.e., before the sub-screen was created). As far as I can tell, the putwin() and getwin() functions can easily solve this problem. So I can do something like this: # draw/write some stuff on stdscr......
0
1902
by: Leo Breebaart | last post by:
On MS Windows, I am trying to find out a good default location to save some temporary files. The tempfile module seemed to have exactly what I wanted: >>> import tempfile >>> tempfile.gettempdir() 'c:\\docume~1\\admini~1\\locals~1\\temp' >>>
6
1388
by: James T. Dennis | last post by:
Tonight I discovered something odd in the __doc__ for tempfile as shipped with Python 2.4.4 and 2.5: it says: This module also provides some data items to the user: TMP_MAX - maximum number of names that will be tried before giving up. template - the default prefix for all temporary names. You may change this to control the default prefix.
4
1129
by: billiejoex | last post by:
Hi all, I would like to use tempfile module to generate files having unique names excepting that I don't want them to be removed after closing. Does it is possible?
9
3747
by: billiejoex | last post by:
Hi there. I'm trying to generate a brand new file with a unique name by using tempfile.mkstemp(). In conjunction I used os.fdopen() to get a wrapper around file properties (write & read methods, and so on...) but 'name' attribute does not contain the correct file name. Why? <fdopen> Moreover, I'd like to know if I'm doing fine. Does this approach avoid
7
578
by: byte8bits | last post by:
Wondering if someone would help me to better understand tempfile. I attempt to create a tempfile, write to it, read it, but it is not behaving as I expect. Any tips? <open file '<fdopen>', mode 'w+b' at 0xab364968> 0 0 0
0
8436
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8345
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8548
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8634
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7371
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4182
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2763
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2000
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1757
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.