summaryrefslogtreecommitdiffstats
path: root/Lib/tempfile.py
blob: 1acd251a55f1c0963d5ce28b908a999be8617ea2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# Temporary file name allocation
#
# XXX This tries to be not UNIX specific, but I don't know beans about
# how to choose a temp directory or filename on MS-DOS or other
# systems so it may have to be changed...


import os


# Parameters that the caller may set to override the defaults

tempdir = None
template = None


# Function to calculate the directory to use

def gettempdir():
    global tempdir
    if tempdir is not None:
	return tempdir
    attempdirs = ['/usr/tmp', '/tmp', os.getcwd(), os.curdir]
    if os.name == 'nt':
	attempdirs.insert(0, 'C:\\TEMP')
	attempdirs.insert(0, '\\TEMP')
    elif os.name == 'mac':
    	import macfs, MACFS
    	try:
    	     refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kTemporaryFolderType, 0)
    	     dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname()
    	     attempdirs.insert(0, dirname)
	except macfs.error:
	    pass
    if os.environ.has_key('TMPDIR'):
	attempdirs.insert(0, os.environ['TMPDIR'])
    testfile = gettempprefix() + 'test'
    for dir in attempdirs:
	try:
	    filename = os.path.join(dir, testfile)
	    fp = open(filename, 'w')
	    fp.write('blat')
	    fp.close()
	    os.unlink(filename)
	    tempdir = dir
	    break
	except IOError:
	    pass
    if tempdir is None:
	msg = "Can't find a usable temporary directory amongst " + `attempdirs`
	raise IOError, msg
    return tempdir


# Function to calculate a prefix of the filename to use

def gettempprefix():
	global template
	if template == None:
		if os.name == 'posix':
			template = '@' + `os.getpid()` + '.'
		elif os.name == 'mac':
			template = 'Python-Tmp-'
		else:
			template = 'tmp' # XXX might choose a better one
	return template


# Counter for generating unique names

counter = 0


# User-callable function to return a unique temporary file name

def mktemp():
	global counter
	dir = gettempdir()
	pre = gettempprefix()
	while 1:
		counter = counter + 1
		file = os.path.join(dir, pre + `counter`)
		if not os.path.exists(file):
			return file