473,659 Members | 2,602 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

tempfile.mkstem p and os.fdopen

Hi there.
I'm trying to generate a brand new file with a unique name by using
tempfile.mkstem p().
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.mkstem p(prefix='ftpd. ', dir=os.getcwd() )
fd = os.fdopen(filen o, '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 3746
On Aug 28, 1:55 pm, billiejoex <gne...@gmail.c omwrote:
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.mkstem p(prefix='ftpd. ', dir=os.getcwd() )
fd = os.fdopen(filen o, '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************ **********@19g2 000hsx.googlegr oups.com>,
billiejoex <gn****@gmail.c omwrote:
Hi there.
I'm trying to generate a brand new file with a unique name by using
tempfile.mkstem p().
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.mkstem p(prefix='ftpd. ', dir=os.getcwd() )
fd = os.fdopen(filen o, '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 NamedTemporaryF ile
classes in the tempfile module -- these expose a file-like API,
including a .name attribute.

Assuming tempfile.mkstem p() 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.c omwrote:
I'm trying to generate a brand new file with a unique name by using
tempfile.mkstem p().

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.mkstem p() and os.fdopen() accept a "mode" argument.
It's not clear *when* do I have to specify such mode. When using
tempfile.mkstem p?
>>fileno, name = tempfile.mkstem p(text=False)
fd = os.fdopen(filen o)
....or when using os.fdopen()?
>>fileno, name = tempfile.mkstem p()
fd = os.fdopen(filen o, mode='wb')
Moreover, what happens if I specify "text" mode when using mkstemp and
"binary" mode when using fdopen?
>>fileno, name = tempfile.mkstem p(text=True)
fd = os.fdopen(filen o, 'wb')

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

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

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

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

--
Gabriel Genellina

Aug 29 '07 #6
On Aug 28, 7:55 pm, billiejoex <gne...@gmail.c omwrote:
Hi there.
I'm trying to generate a brand new file with a unique name by using
tempfile.mkstem p().
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__(sel f, attr):
return getattr(self._f ileobj, attr)

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

Aug 29 '07 #7
In message <Michael.J.From berger-8FC07C.15483428 082007@localhos t>, 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.From berger-8FC07C.15483428 082007@localhos t>, 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
NamedTemporaryF ile 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
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
1748
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 on posix systems TemporaryFile returns an actual file (the result of os.fdopen()) and on windows, TemporaryFile returns a file wrapper which forwards getattr calls to the underlying file.
5
2574
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 function is working right because I get the randomized name in the text string and the function does return an integer value as well as leaving a new file of the same name. What I haven't been able to do is write to it.
5
1701
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 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
0
1202
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
1387
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?
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
8341
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,...
0
8751
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8539
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
8630
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...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4176
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
2759
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
1982
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1739
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.