473,326 Members | 2,255 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

tempfile.mkstemp and os.fdopen

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?
>>import os
import tempfile
fileno, name = tempfile.mkstemp(prefix='ftpd.', dir=os.getcwd())
fd = os.fdopen(fileno, 'wb')
fd.name
<fdopen>

Moreover, I'd like to know if I'm doing fine. Does this approach avoid
race conditions or other types of security problems?

Thanks in advance

Aug 28 '07 #1
9 3718
On Aug 28, 1:55 pm, billiejoex <gne...@gmail.comwrote:
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?
>import os
import tempfile
fileno, name = tempfile.mkstemp(prefix='ftpd.', dir=os.getcwd())
fd = os.fdopen(fileno, 'wb')
fd.name

<fdopen>

Moreover, I'd like to know if I'm doing fine. Does this approach avoid
race conditions or other types of security problems?

Thanks in advance
There seems to be a feature request for this:

http://bugs.python.org/issue1625576


Aug 28 '07 #2
In article <11**********************@19g2000hsx.googlegroups. com>,
billiejoex <gn****@gmail.comwrote:
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?
>import os
import tempfile
fileno, name = tempfile.mkstemp(prefix='ftpd.', dir=os.getcwd())
fd = os.fdopen(fileno, 'wb')
fd.name
<fdopen>

Moreover, I'd like to know if I'm doing fine. Does this approach avoid
race conditions or other types of security problems?

Thanks in advance
In brief, since os.fdopen() only has access to the file descriptor, it
does not have a convenient way to obtain the file's name. However, you
might also want to look at the TemporaryFile and NamedTemporaryFile
classes in the tempfile module -- these expose a file-like API,
including a .name attribute.

Assuming tempfile.mkstemp() is implemented properly, I think what you
are doing should be sufficient to avoid the obvious file-creation race
condition.

Cheers,
-M

--
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA
Aug 28 '07 #3
billiejoex <gn****@gmail.comwrote:
I'm trying to generate a brand new file with a unique name by using
tempfile.mkstemp().

Moreover, I'd like to know if I'm doing fine. Does this approach avoid
race conditions
This is a reasonably secure way of doing things. It can't race under
unix at least (dunno about windows) unless your dir is on NFS.

If you want more security then make sure dir isn't publically
writeable.

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Aug 28 '07 #4
Thanks all.
Another question: I have to open file for writing ('wb') but I noticed
that both tempfile.mkstemp() and os.fdopen() accept a "mode" argument.
It's not clear *when* do I have to specify such mode. When using
tempfile.mkstemp?
>>fileno, name = tempfile.mkstemp(text=False)
fd = os.fdopen(fileno)
....or when using os.fdopen()?
>>fileno, name = tempfile.mkstemp()
fd = os.fdopen(fileno, mode='wb')
Moreover, what happens if I specify "text" mode when using mkstemp and
"binary" mode when using fdopen?
>>fileno, name = tempfile.mkstemp(text=True)
fd = os.fdopen(fileno, 'wb')

PS - I think that tempfile.mkstemp docstring should be enhanced to
cover such and other questions (e.g. I find reasonable that every user
using tempfile.mkstemp() should use also os.fdopen() in conjunction
but this isn't mentioned).

Aug 29 '07 #5
On 28 ago, 22:21, billiejoex <gne...@gmail.comwrote:
Another question: I have to open file for writing ('wb') but I noticed
that both tempfile.mkstemp() and os.fdopen() accept a "mode" argument.
It's not clear *when* do I have to specify such mode. When using
tempfile.mkstemp?

Moreover, what happens if I specify "text" mode when using mkstemp and
"binary" mode when using fdopen?

PS - I think that tempfile.mkstemp docstring should be enhanced to
cover such and other questions (e.g. I find reasonable that every user
using tempfile.mkstemp() should use also os.fdopen() in conjunction
but this isn't mentioned).
As someone already suggested, why don't you use TemporaryFile or
NamedTemporaryFile and avoid such problems?

--
Gabriel Genellina

Aug 29 '07 #6
On Aug 28, 7:55 pm, billiejoex <gne...@gmail.comwrote:
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?
import tempfile, os

class TempFile(object):

def __init__(self, fd, fname):
self._fileobj = os.fdopen(fd, 'w+b')
self.name = fname

def __getattr__(self, attr):
return getattr(self._fileobj, attr)

def mktempfile(dir=None, suffix='.tmp'):
return TempFile(*tempfile.mkstemp(dir=dir, suffix=suffix))

Aug 29 '07 #7
In message <Michael.J.Fromberger-8FC07C.15483428082007@localhost>, Michael
J. Fromberger wrote:
... since os.fdopen() only has access to the file descriptor, it
does not have a convenient way to obtain the file's name.
You can do this under Linux as follows:

os.readlink("/proc/%d/fd/%d" % (os.getpid(), fileno))

Aug 29 '07 #8
Lawrence D'Oliveiro <ld*@geek-central.gen.new_zealandwrote:
In message <Michael.J.Fromberger-8FC07C.15483428082007@localhost>, Michael
J. Fromberger wrote:
... since os.fdopen() only has access to the file descriptor, it
does not have a convenient way to obtain the file's name.

You can do this under Linux as follows:

os.readlink("/proc/%d/fd/%d" % (os.getpid(), fileno))
A good idea! You can write this slightly more succinctly as

os.readlink("/proc/self/fd/%d" % fileno)

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Aug 29 '07 #9
Gabriel Genellina wrote:
As someone already suggested, why don't you use TemporaryFile or
NamedTemporaryFile and avoid such problems?
Because I don't want file to be removed after closing.

Aug 29 '07 #10

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

Similar topics

3
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...
2
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 --...
1
by: Jonathan Wright | last post by:
import tempfile import types print isinstance(tempfile.TemporaryFile(), types.FileType) Prints False on Windows and True on linux or any other posix system. The reason for the difference is...
5
by: Martin McCormick | last post by:
I am obviously confused about how to write to the file created by the mkstemp function. The manual says that it returns a pointer to a file descripter when successful and I think that the...
5
by: Gregory Piñero | last post by:
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...
0
by: Colin Wildsmith | last post by:
Hello, I am trying to create a temp file, however the file that is created is still there after the program has completed. Why is this so? CoLe #!/usr/bin/python import os, tempfile, sys
6
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...
4
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?
7
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.