|
1 | 1 | # 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... |
2 | 6 |
|
3 | | -import posix |
4 | | -import path |
5 | 7 |
|
| 8 | +import os |
6 | 9 |
|
7 | | -# Changeable parameters (by clients!)... |
8 | 10 |
|
9 | | -tempdir = '/usr/tmp' |
10 | | -template = '@' |
| 11 | +# Parameters that the caller may set to override the defaults |
11 | 12 |
|
12 | | -# Use environment variable $TMPDIR to override default tempdir. |
| 13 | +tempdir = None |
| 14 | +template = None |
13 | 15 |
|
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 |
17 | 42 |
|
18 | 43 |
|
19 | 44 | # Counter for generating unique names |
20 | 45 |
|
21 | 46 | counter = 0 |
22 | 47 |
|
23 | 48 |
|
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 |
28 | 50 |
|
29 | 51 | def mktemp(): |
30 | 52 | global counter |
| 53 | + dir = gettempdir() |
| 54 | + pre = gettempprefix() |
31 | 55 | 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