473,372 Members | 989 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,372 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 3723
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...
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.