blob: 5b05bdd1b365f572da54b8a3f1a7701b68270f86 [file] [log] [blame]
Guido van Rossume7b146f2000-02-04 15:28:42 +00001"""Temporary files and filenames."""
2
Guido van Rossum41f95031992-03-31 19:02:01 +00003# 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...
Guido van Rossumeee94981991-11-12 15:38:08 +00006
7
Guido van Rossum41f95031992-03-31 19:02:01 +00008import os
Guido van Rossumeee94981991-11-12 15:38:08 +00009
Guido van Rossumeee94981991-11-12 15:38:08 +000010
Guido van Rossum41f95031992-03-31 19:02:01 +000011# Parameters that the caller may set to override the defaults
Guido van Rossumcff34541992-01-14 18:31:56 +000012
Guido van Rossum41f95031992-03-31 19:02:01 +000013tempdir = None
14template = None
15
16
Guido van Rossum41f95031992-03-31 19:02:01 +000017def gettempdir():
Guido van Rossume7b146f2000-02-04 15:28:42 +000018 """Function to calculate the directory to use."""
Guido van Rossumf4aaf861996-05-28 23:31:34 +000019 global tempdir
Guido van Rossum4033ad71996-08-08 18:33:56 +000020 if tempdir is not None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000021 return tempdir
Guido van Rossum29e5f5d1998-04-09 14:27:57 +000022 try:
23 pwd = os.getcwd()
24 except (AttributeError, os.error):
25 pwd = os.curdir
26 attempdirs = ['/usr/tmp', '/tmp', pwd]
Guido van Rossum3e065ad1996-08-20 20:38:59 +000027 if os.name == 'nt':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000028 attempdirs.insert(0, 'C:\\TEMP')
29 attempdirs.insert(0, '\\TEMP')
Guido van Rossumf4f756c1997-04-11 19:00:53 +000030 elif os.name == 'mac':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000031 import macfs, MACFS
32 try:
33 refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk,
Guido van Rossum57a06611998-04-28 16:03:34 +000034 MACFS.kTemporaryFolderType, 1)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000035 dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname()
36 attempdirs.insert(0, dirname)
37 except macfs.error:
38 pass
Guido van Rossumca549821997-08-12 18:00:12 +000039 for envname in 'TMPDIR', 'TEMP', 'TMP':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000040 if os.environ.has_key(envname):
41 attempdirs.insert(0, os.environ[envname])
Guido van Rossum3e065ad1996-08-20 20:38:59 +000042 testfile = gettempprefix() + 'test'
Guido van Rossumf4aaf861996-05-28 23:31:34 +000043 for dir in attempdirs:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000044 try:
45 filename = os.path.join(dir, testfile)
46 fp = open(filename, 'w')
47 fp.write('blat')
48 fp.close()
49 os.unlink(filename)
50 tempdir = dir
51 break
52 except IOError:
53 pass
Guido van Rossumf4aaf861996-05-28 23:31:34 +000054 if tempdir is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000055 msg = "Can't find a usable temporary directory amongst " + `attempdirs`
56 raise IOError, msg
Guido van Rossumf4aaf861996-05-28 23:31:34 +000057 return tempdir
Guido van Rossum41f95031992-03-31 19:02:01 +000058
59
Guido van Rossumb0e57181998-10-14 20:27:05 +000060_pid = None
61
Guido van Rossum41f95031992-03-31 19:02:01 +000062def gettempprefix():
Guido van Rossume7b146f2000-02-04 15:28:42 +000063 """Function to calculate a prefix of the filename to use."""
Guido van Rossumb0e57181998-10-14 20:27:05 +000064 global template, _pid
65 if os.name == 'posix' and _pid and _pid != os.getpid():
66 # Our pid changed; we must have forked -- zap the template
67 template = None
68 if template is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000069 if os.name == 'posix':
Guido van Rossumb0e57181998-10-14 20:27:05 +000070 _pid = os.getpid()
71 template = '@' + `_pid` + '.'
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000072 elif os.name == 'nt':
73 template = '~' + `os.getpid()` + '-'
74 elif os.name == 'mac':
75 template = 'Python-Tmp-'
76 else:
77 template = 'tmp' # XXX might choose a better one
78 return template
Guido van Rossumcff34541992-01-14 18:31:56 +000079
Guido van Rossumeee94981991-11-12 15:38:08 +000080
Guido van Rossum4a3a41f1991-12-26 13:10:50 +000081# Counter for generating unique names
Guido van Rossumeee94981991-11-12 15:38:08 +000082
Guido van Rossum4a3a41f1991-12-26 13:10:50 +000083counter = 0
Guido van Rossumeee94981991-11-12 15:38:08 +000084
85
Guido van Rossumb8c42c91997-12-19 04:29:50 +000086def mktemp(suffix=""):
Guido van Rossume7b146f2000-02-04 15:28:42 +000087 """User-callable function to return a unique temporary file name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000088 global counter
89 dir = gettempdir()
90 pre = gettempprefix()
91 while 1:
92 counter = counter + 1
93 file = os.path.join(dir, pre + `counter` + suffix)
94 if not os.path.exists(file):
95 return file
Guido van Rossumca549821997-08-12 18:00:12 +000096
97
98class TemporaryFileWrapper:
99 """Temporary file wrapper
100
101 This class provides a wrapper around files opened for temporary use.
102 In particular, it seeks to automatically remove the file when it is
103 no longer needed.
104 """
105 def __init__(self, file, path):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000106 self.file = file
107 self.path = path
Guido van Rossumca549821997-08-12 18:00:12 +0000108
109 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000110 self.file.close()
111 os.unlink(self.path)
Guido van Rossumca549821997-08-12 18:00:12 +0000112
113 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000114 try: self.close()
115 except: pass
Guido van Rossumca549821997-08-12 18:00:12 +0000116
117 def __getattr__(self, name):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000118 file = self.__dict__['file']
119 a = getattr(file, name)
Guido van Rossum6b708d51999-06-01 18:55:36 +0000120 if type(a) != type(0):
121 setattr(self, name, a)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000122 return a
Guido van Rossumca549821997-08-12 18:00:12 +0000123
124
Guido van Rossumb8c42c91997-12-19 04:29:50 +0000125def TemporaryFile(mode='w+b', bufsize=-1, suffix=""):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000126 """Create and return a temporary file (opened read-write by default)."""
Guido van Rossumb8c42c91997-12-19 04:29:50 +0000127 name = mktemp(suffix)
Guido van Rossumdce3d551998-10-24 01:34:45 +0000128 if os.name == 'posix':
129 # Unix -- be very careful
130 fd = os.open(name, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700)
Guido van Rossum2457fc21998-10-24 15:02:59 +0000131 try:
132 os.unlink(name)
133 return os.fdopen(fd, mode, bufsize)
134 except:
135 os.close(fd)
136 raise
Guido van Rossumca549821997-08-12 18:00:12 +0000137 else:
Guido van Rossumdce3d551998-10-24 01:34:45 +0000138 # Non-unix -- can't unlink file that's still open, use wrapper
139 file = open(name, mode, bufsize)
140 return TemporaryFileWrapper(file, name)