Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 41f9503

Browse files
committed
Mostly rewritten to be more flexible and more portable
./
1 parent 1a76ef2 commit 41f9503

1 file changed

Lines changed: 41 additions & 18 deletions

File tree

Lib/tempfile.py

Lines changed: 41 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,59 @@
11
# Temporary file name allocation
2+
#
3+
# XXX This tries to be not UNIX specific, but I don't know beans about
4+
# how to choose a temp directory or filename on MS-DOS or other
5+
# systems so it may have to be changed...
26

3-
import posix
4-
import path
57

8+
import os
69

7-
# Changeable parameters (by clients!)...
810

9-
tempdir = '/usr/tmp'
10-
template = '@'
11+
# Parameters that the caller may set to override the defaults
1112

12-
# Use environment variable $TMPDIR to override default tempdir.
13+
tempdir = None
14+
template = None
1315

14-
if posix.environ.has_key('TMPDIR'):
15-
# XXX Could check that it's a writable directory...
16-
tempdir = posix.environ['TMPDIR']
16+
17+
# Function to calculate the directory to use
18+
19+
def gettempdir():
20+
global tempdir
21+
if tempdir == None:
22+
try:
23+
tempdir = os.environ['TMPDIR']
24+
except (KeyError, AttributeError):
25+
if os.name == 'posix':
26+
tempdir = '/usr/tmp' # XXX Why not /tmp?
27+
else:
28+
tempdir = os.getcwd() # XXX Is this OK?
29+
return tempdir
30+
31+
32+
# Function to calculate a prefix of the filename to use
33+
34+
def gettempprefix():
35+
global template
36+
if template == None:
37+
if os.name == 'posix':
38+
template = '@' + `os.getpid()` + '.'
39+
else:
40+
template = 'tmp' # XXX might choose a better one
41+
return template
1742

1843

1944
# Counter for generating unique names
2045

2146
counter = 0
2247

2348

24-
# User-callable function
25-
# XXX Should this have a parameter, like C's mktemp()?
26-
# XXX Should we instead use the model of Standard C's tempnam()?
27-
# XXX By all means, avoid a mess with four different functions like C...
49+
# User-callable function to return a unique temporary file name
2850

2951
def mktemp():
3052
global counter
53+
dir = gettempdir()
54+
pre = gettempprefix()
3155
while 1:
32-
counter = counter+1
33-
file = tempdir+'/'+template+`posix.getpid()`+'.'+`counter`
34-
if not path.exists(file):
35-
break
36-
return file
56+
counter = counter + 1
57+
file = os.path.join(dir, pre + `counter`)
58+
if not os.path.exists(file):
59+
return file

0 commit comments

Comments
 (0)