blob: 5b79981dffe525be4f6dd03e2eed8cd6f21dbbf3 [file] [log] [blame]
Ka-Ping Yeefeb67192001-03-02 23:31:43 +00001r"""OS routines for Mac, DOS, NT, or Posix depending on what system we're on.
Guido van Rossum31104f41992-01-14 18:28:36 +00002
Guido van Rossum54f22ed2000-02-04 15:10:34 +00003This exports:
Martin v. Löwis8b10f892002-10-09 17:23:29 +00004 - all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
5 - os.path is one of the modules posixpath, ntpath, or macpath
6 - os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'
Guido van Rossum54f22ed2000-02-04 15:10:34 +00007 - os.curdir is a string representing the current directory ('.' or ':')
8 - os.pardir is a string representing the parent directory ('..' or '::')
9 - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
Guido van Rossume2ae77b2001-10-24 20:42:55 +000010 - os.extsep is the extension separator ('.' or '/')
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000011 - os.altsep is the alternate pathname separator (None or '/')
Guido van Rossum54f22ed2000-02-04 15:10:34 +000012 - os.pathsep is the component separator used in $PATH etc
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000013 - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
Guido van Rossum54f22ed2000-02-04 15:10:34 +000014 - os.defpath is the default search path for executables
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000015 - os.devnull is the file path of the null device ('/dev/null', etc.)
Guido van Rossum31104f41992-01-14 18:28:36 +000016
Guido van Rossum54f22ed2000-02-04 15:10:34 +000017Programs that import and use 'os' stand a better chance of being
18portable between different platforms. Of course, they must then
19only use functions that are defined by all platforms (e.g., unlink
20and opendir), and leave all pathname manipulation to os.path
21(e.g., split and join).
22"""
Guido van Rossum31104f41992-01-14 18:28:36 +000023
Skip Montanaro269b83b2001-02-06 01:07:02 +000024#'
25
Guido van Rossum2979b011994-08-01 11:18:30 +000026import sys
Guido van Rossuma28dab51997-08-29 22:36:47 +000027
28_names = sys.builtin_module_names
29
Tim Petersc4e09402003-04-25 07:11:48 +000030# Note: more names are added to __all__ later.
Skip Montanaro6c0a0e12001-02-28 01:00:58 +000031__all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000032 "defpath", "name", "path", "devnull"]
Skip Montanaro269b83b2001-02-06 01:07:02 +000033
34def _get_exports_list(module):
35 try:
36 return list(module.__all__)
37 except AttributeError:
38 return [n for n in dir(module) if n[0] != '_']
39
Guido van Rossuma28dab51997-08-29 22:36:47 +000040if 'posix' in _names:
Guido van Rossum61de0ac1997-12-05 21:24:30 +000041 name = 'posix'
Guido van Rossume9387ea1998-05-22 15:26:04 +000042 linesep = '\n'
Guido van Rossum61de0ac1997-12-05 21:24:30 +000043 from posix import *
44 try:
45 from posix import _exit
46 except ImportError:
47 pass
Skip Montanaro117910d2003-02-14 19:35:31 +000048 import posixpath as path
Tim Petersf2715e02003-02-19 02:35:07 +000049
Skip Montanaro269b83b2001-02-06 01:07:02 +000050 import posix
51 __all__.extend(_get_exports_list(posix))
52 del posix
53
Guido van Rossuma28dab51997-08-29 22:36:47 +000054elif 'nt' in _names:
Guido van Rossum61de0ac1997-12-05 21:24:30 +000055 name = 'nt'
Guido van Rossume9387ea1998-05-22 15:26:04 +000056 linesep = '\r\n'
Guido van Rossum61de0ac1997-12-05 21:24:30 +000057 from nt import *
Tim Peters6757c1e2003-01-08 21:20:57 +000058 try:
59 from nt import _exit
60 except ImportError:
61 pass
Skip Montanaro117910d2003-02-14 19:35:31 +000062 import ntpath as path
Tim Petersf2715e02003-02-19 02:35:07 +000063
Skip Montanaro269b83b2001-02-06 01:07:02 +000064 import nt
65 __all__.extend(_get_exports_list(nt))
66 del nt
67
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000068elif 'os2' in _names:
Guido van Rossum61de0ac1997-12-05 21:24:30 +000069 name = 'os2'
Guido van Rossume9387ea1998-05-22 15:26:04 +000070 linesep = '\r\n'
Guido van Rossum61de0ac1997-12-05 21:24:30 +000071 from os2 import *
72 try:
73 from os2 import _exit
74 except ImportError:
75 pass
Andrew MacIntyre5cef5712002-02-24 05:32:32 +000076 if sys.version.find('EMX GCC') == -1:
Skip Montanaro117910d2003-02-14 19:35:31 +000077 import ntpath as path
Andrew MacIntyre5cef5712002-02-24 05:32:32 +000078 else:
Skip Montanaro117910d2003-02-14 19:35:31 +000079 import os2emxpath as path
Andrew MacIntyre89f98652003-12-02 12:33:01 +000080 from _emx_link import link
Tim Petersf2715e02003-02-19 02:35:07 +000081
Skip Montanaro269b83b2001-02-06 01:07:02 +000082 import os2
83 __all__.extend(_get_exports_list(os2))
84 del os2
85
Guido van Rossuma28dab51997-08-29 22:36:47 +000086elif 'mac' in _names:
Guido van Rossum61de0ac1997-12-05 21:24:30 +000087 name = 'mac'
Guido van Rossume9387ea1998-05-22 15:26:04 +000088 linesep = '\r'
Guido van Rossum61de0ac1997-12-05 21:24:30 +000089 from mac import *
90 try:
91 from mac import _exit
92 except ImportError:
93 pass
Skip Montanaro117910d2003-02-14 19:35:31 +000094 import macpath as path
Tim Petersf2715e02003-02-19 02:35:07 +000095
Skip Montanaro269b83b2001-02-06 01:07:02 +000096 import mac
97 __all__.extend(_get_exports_list(mac))
98 del mac
99
Guido van Rossum18df5d41999-06-11 01:37:27 +0000100elif 'ce' in _names:
101 name = 'ce'
102 linesep = '\r\n'
Guido van Rossum18df5d41999-06-11 01:37:27 +0000103 from ce import *
Tim Peters6757c1e2003-01-08 21:20:57 +0000104 try:
105 from ce import _exit
106 except ImportError:
107 pass
Guido van Rossum18df5d41999-06-11 01:37:27 +0000108 # We can use the standard Windows path.
Skip Montanaro117910d2003-02-14 19:35:31 +0000109 import ntpath as path
Tim Petersf2715e02003-02-19 02:35:07 +0000110
Skip Montanaro269b83b2001-02-06 01:07:02 +0000111 import ce
112 __all__.extend(_get_exports_list(ce))
113 del ce
114
Guido van Rossumd74fb6b2001-03-02 06:43:49 +0000115elif 'riscos' in _names:
116 name = 'riscos'
117 linesep = '\n'
Guido van Rossumd74fb6b2001-03-02 06:43:49 +0000118 from riscos import *
119 try:
120 from riscos import _exit
121 except ImportError:
122 pass
Skip Montanaro117910d2003-02-14 19:35:31 +0000123 import riscospath as path
Tim Petersf2715e02003-02-19 02:35:07 +0000124
Guido van Rossumd74fb6b2001-03-02 06:43:49 +0000125 import riscos
126 __all__.extend(_get_exports_list(riscos))
Skip Montanaro81e4b1c2001-03-06 15:26:07 +0000127 del riscos
Guido van Rossumd74fb6b2001-03-02 06:43:49 +0000128
Guido van Rossum2979b011994-08-01 11:18:30 +0000129else:
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000130 raise ImportError, 'no os specific module found'
Guido van Rossume65cce51993-11-08 15:05:21 +0000131
Skip Montanaro117910d2003-02-14 19:35:31 +0000132sys.modules['os.path'] = path
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000133from os.path import curdir, pardir, sep, pathsep, defpath, extsep, altsep, \
134 devnull
Skip Montanaro269b83b2001-02-06 01:07:02 +0000135
Guido van Rossuma28dab51997-08-29 22:36:47 +0000136del _names
137
Skip Montanaro269b83b2001-02-06 01:07:02 +0000138#'
139
Guido van Rossum4def7de1998-07-24 20:48:03 +0000140# Super directory utilities.
141# (Inspired by Eric Raymond; the doc strings are mostly his)
142
143def makedirs(name, mode=0777):
Fred Drakecadb9eb2002-07-02 21:28:04 +0000144 """makedirs(path [, mode=0777])
Guido van Rossum4def7de1998-07-24 20:48:03 +0000145
146 Super-mkdir; create a leaf directory and all intermediate ones.
147 Works like mkdir, except that any intermediate path segment (not
148 just the rightmost) will be created if it does not exist. This is
149 recursive.
150
151 """
152 head, tail = path.split(name)
Fred Drake9f2550f2000-07-25 15:16:40 +0000153 if not tail:
154 head, tail = path.split(head)
Guido van Rossum4def7de1998-07-24 20:48:03 +0000155 if head and tail and not path.exists(head):
156 makedirs(head, mode)
Andrew M. Kuchling6fccc8a2003-12-23 16:33:28 +0000157 if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists
158 return
Guido van Rossum4def7de1998-07-24 20:48:03 +0000159 mkdir(name, mode)
160
161def removedirs(name):
Fred Drakecadb9eb2002-07-02 21:28:04 +0000162 """removedirs(path)
Guido van Rossum4def7de1998-07-24 20:48:03 +0000163
164 Super-rmdir; remove a leaf directory and empty all intermediate
165 ones. Works like rmdir except that, if the leaf directory is
166 successfully removed, directories corresponding to rightmost path
Tim Petersc4e09402003-04-25 07:11:48 +0000167 segments will be pruned away until either the whole path is
Guido van Rossum4def7de1998-07-24 20:48:03 +0000168 consumed or an error occurs. Errors during this latter phase are
169 ignored -- they generally mean that a directory was not empty.
170
171 """
172 rmdir(name)
173 head, tail = path.split(name)
Fred Drake9f2550f2000-07-25 15:16:40 +0000174 if not tail:
175 head, tail = path.split(head)
Guido van Rossum4def7de1998-07-24 20:48:03 +0000176 while head and tail:
177 try:
178 rmdir(head)
179 except error:
180 break
181 head, tail = path.split(head)
182
183def renames(old, new):
Fred Drakecadb9eb2002-07-02 21:28:04 +0000184 """renames(old, new)
Guido van Rossum4def7de1998-07-24 20:48:03 +0000185
186 Super-rename; create directories as necessary and delete any left
187 empty. Works like rename, except creation of any intermediate
188 directories needed to make the new pathname good is attempted
189 first. After the rename, directories corresponding to rightmost
190 path segments of the old name will be pruned way until either the
191 whole path is consumed or a nonempty directory is found.
192
193 Note: this function can fail with the new directory structure made
194 if you lack permissions needed to unlink the leaf directory or
195 file.
196
197 """
198 head, tail = path.split(new)
199 if head and tail and not path.exists(head):
200 makedirs(head)
201 rename(old, new)
202 head, tail = path.split(old)
203 if head and tail:
204 try:
205 removedirs(head)
206 except error:
207 pass
208
Skip Montanaro269b83b2001-02-06 01:07:02 +0000209__all__.extend(["makedirs", "removedirs", "renames"])
210
Guido van Rossumbf1bef82003-05-13 18:01:19 +0000211def walk(top, topdown=True, onerror=None):
Tim Petersc4e09402003-04-25 07:11:48 +0000212 """Directory tree generator.
213
214 For each directory in the directory tree rooted at top (including top
215 itself, but excluding '.' and '..'), yields a 3-tuple
216
217 dirpath, dirnames, filenames
218
219 dirpath is a string, the path to the directory. dirnames is a list of
220 the names of the subdirectories in dirpath (excluding '.' and '..').
221 filenames is a list of the names of the non-directory files in dirpath.
222 Note that the names in the lists are just names, with no path components.
223 To get a full path (which begins with top) to a file or directory in
224 dirpath, do os.path.join(dirpath, name).
225
226 If optional arg 'topdown' is true or not specified, the triple for a
227 directory is generated before the triples for any of its subdirectories
228 (directories are generated top down). If topdown is false, the triple
229 for a directory is generated after the triples for all of its
230 subdirectories (directories are generated bottom up).
231
232 When topdown is true, the caller can modify the dirnames list in-place
233 (e.g., via del or slice assignment), and walk will only recurse into the
234 subdirectories whose names remain in dirnames; this can be used to prune
235 the search, or to impose a specific order of visiting. Modifying
236 dirnames when topdown is false is ineffective, since the directories in
237 dirnames have already been generated by the time dirnames itself is
238 generated.
239
Guido van Rossumbf1bef82003-05-13 18:01:19 +0000240 By default errors from the os.listdir() call are ignored. If
241 optional arg 'onerror' is specified, it should be a function; it
242 will be called with one argument, an os.error instance. It can
243 report the error to continue with the walk, or raise the exception
244 to abort the walk. Note that the filename is available as the
245 filename attribute of the exception object.
246
Tim Petersc4e09402003-04-25 07:11:48 +0000247 Caution: if you pass a relative pathname for top, don't change the
248 current working directory between resumptions of walk. walk never
249 changes the current directory, and assumes that the client doesn't
250 either.
251
252 Example:
253
254 from os.path import join, getsize
255 for root, dirs, files in walk('python/Lib/email'):
256 print root, "consumes",
257 print sum([getsize(join(root, name)) for name in files]),
258 print "bytes in", len(files), "non-directory files"
259 if 'CVS' in dirs:
260 dirs.remove('CVS') # don't visit CVS directories
261 """
262
263 from os.path import join, isdir, islink
264
265 # We may not have read permission for top, in which case we can't
266 # get a list of the files the directory contains. os.path.walk
267 # always suppressed the exception then, rather than blow up for a
268 # minor reason when (say) a thousand readable directories are still
269 # left to visit. That logic is copied here.
270 try:
271 # Note that listdir and error are globals in this module due
272 # to earlier import-*.
273 names = listdir(top)
Guido van Rossumbf1bef82003-05-13 18:01:19 +0000274 except error, err:
275 if onerror is not None:
276 onerror(err)
Tim Petersc4e09402003-04-25 07:11:48 +0000277 return
278
279 dirs, nondirs = [], []
280 for name in names:
281 if isdir(join(top, name)):
282 dirs.append(name)
283 else:
284 nondirs.append(name)
285
286 if topdown:
287 yield top, dirs, nondirs
288 for name in dirs:
289 path = join(top, name)
290 if not islink(path):
Guido van Rossumbf1bef82003-05-13 18:01:19 +0000291 for x in walk(path, topdown, onerror):
Tim Petersc4e09402003-04-25 07:11:48 +0000292 yield x
293 if not topdown:
294 yield top, dirs, nondirs
295
296__all__.append("walk")
297
Guido van Rossuma28dab51997-08-29 22:36:47 +0000298# Make sure os.environ exists, at least
299try:
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000300 environ
Guido van Rossuma28dab51997-08-29 22:36:47 +0000301except NameError:
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000302 environ = {}
Guido van Rossuma28dab51997-08-29 22:36:47 +0000303
Guido van Rossume65cce51993-11-08 15:05:21 +0000304def execl(file, *args):
Guido van Rossum7da3cc52000-04-25 10:53:22 +0000305 """execl(file, *args)
306
307 Execute the executable file with argument list args, replacing the
308 current process. """
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000309 execv(file, args)
Guido van Rossume65cce51993-11-08 15:05:21 +0000310
311def execle(file, *args):
Guido van Rossum7da3cc52000-04-25 10:53:22 +0000312 """execle(file, *args, env)
313
314 Execute the executable file with argument list args and
315 environment env, replacing the current process. """
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000316 env = args[-1]
317 execve(file, args[:-1], env)
Guido van Rossume65cce51993-11-08 15:05:21 +0000318
319def execlp(file, *args):
Guido van Rossum7da3cc52000-04-25 10:53:22 +0000320 """execlp(file, *args)
321
322 Execute the executable file (which is searched for along $PATH)
323 with argument list args, replacing the current process. """
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000324 execvp(file, args)
Guido van Rossume65cce51993-11-08 15:05:21 +0000325
Guido van Rossum030afb11995-03-14 17:27:18 +0000326def execlpe(file, *args):
Guido van Rossum7da3cc52000-04-25 10:53:22 +0000327 """execlpe(file, *args, env)
328
329 Execute the executable file (which is searched for along $PATH)
330 with argument list args and environment env, replacing the current
Tim Peters2344fae2001-01-15 00:50:52 +0000331 process. """
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000332 env = args[-1]
333 execvpe(file, args[:-1], env)
Guido van Rossum030afb11995-03-14 17:27:18 +0000334
Guido van Rossume65cce51993-11-08 15:05:21 +0000335def execvp(file, args):
Guido van Rossum7da3cc52000-04-25 10:53:22 +0000336 """execp(file, args)
337
338 Execute the executable file (which is searched for along $PATH)
339 with argument list args, replacing the current process.
Thomas Wouters7e474022000-07-16 12:04:32 +0000340 args may be a list or tuple of strings. """
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000341 _execvpe(file, args)
Guido van Rossum030afb11995-03-14 17:27:18 +0000342
343def execvpe(file, args, env):
Guido van Rossum683c0fe2002-09-03 16:36:17 +0000344 """execvpe(file, args, env)
Guido van Rossum7da3cc52000-04-25 10:53:22 +0000345
346 Execute the executable file (which is searched for along $PATH)
347 with argument list args and environment env , replacing the
348 current process.
Tim Peters2344fae2001-01-15 00:50:52 +0000349 args may be a list or tuple of strings. """
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000350 _execvpe(file, args, env)
Guido van Rossum030afb11995-03-14 17:27:18 +0000351
Skip Montanaro269b83b2001-02-06 01:07:02 +0000352__all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])
353
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000354def _execvpe(file, args, env=None):
Guido van Rossumaed51d82002-08-05 16:13:24 +0000355 from errno import ENOENT, ENOTDIR
356
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000357 if env is not None:
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000358 func = execve
359 argrest = (args, env)
360 else:
361 func = execv
362 argrest = (args,)
363 env = environ
Guido van Rossumaed51d82002-08-05 16:13:24 +0000364
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000365 head, tail = path.split(file)
366 if head:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000367 func(file, *argrest)
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000368 return
Raymond Hettinger54f02222002-06-01 14:18:47 +0000369 if 'PATH' in env:
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000370 envpath = env['PATH']
371 else:
372 envpath = defpath
Guido van Rossum965fdae2000-04-04 19:50:04 +0000373 PATH = envpath.split(pathsep)
Guido van Rossum683c0fe2002-09-03 16:36:17 +0000374 saved_exc = None
375 saved_tb = None
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000376 for dir in PATH:
377 fullname = path.join(dir, file)
378 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000379 func(fullname, *argrest)
Guido van Rossum683c0fe2002-09-03 16:36:17 +0000380 except error, e:
381 tb = sys.exc_info()[2]
382 if (e.errno != ENOENT and e.errno != ENOTDIR
383 and saved_exc is None):
384 saved_exc = e
385 saved_tb = tb
386 if saved_exc:
387 raise error, saved_exc, saved_tb
388 raise error, e, tb
Guido van Rossumd74fb6b2001-03-02 06:43:49 +0000389
Martin v. Löwisa90f4382001-03-07 09:05:45 +0000390# Change environ to automatically call putenv() if it exists
391try:
392 # This will fail if there's no putenv
393 putenv
394except NameError:
395 pass
396else:
397 import UserDict
Guido van Rossum3b8e20d1996-07-24 00:55:17 +0000398
Guido van Rossumc524d952001-10-19 01:31:59 +0000399 # Fake unsetenv() for Windows
Martin v. Löwis8b10f892002-10-09 17:23:29 +0000400 # not sure about os2 here but
Guido van Rossumc524d952001-10-19 01:31:59 +0000401 # I'm guessing they are the same.
402
Martin v. Löwis8b10f892002-10-09 17:23:29 +0000403 if name in ('os2', 'nt'):
Guido van Rossumc524d952001-10-19 01:31:59 +0000404 def unsetenv(key):
405 putenv(key, "")
406
Martin v. Löwisa90f4382001-03-07 09:05:45 +0000407 if name == "riscos":
408 # On RISC OS, all env access goes through getenv and putenv
409 from riscosenviron import _Environ
Martin v. Löwis8b10f892002-10-09 17:23:29 +0000410 elif name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE
Guido van Rossumda4d6da1998-08-04 16:01:23 +0000411 # But we store them as upper case
Raymond Hettingerca2f5372002-09-06 19:36:31 +0000412 class _Environ(UserDict.IterableUserDict):
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000413 def __init__(self, environ):
414 UserDict.UserDict.__init__(self)
Guido van Rossumda4d6da1998-08-04 16:01:23 +0000415 data = self.data
Guido van Rossumda4d6da1998-08-04 16:01:23 +0000416 for k, v in environ.items():
Guido van Rossum965fdae2000-04-04 19:50:04 +0000417 data[k.upper()] = v
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000418 def __setitem__(self, key, item):
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000419 putenv(key, item)
Guido van Rossum965fdae2000-04-04 19:50:04 +0000420 self.data[key.upper()] = item
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000421 def __getitem__(self, key):
Guido van Rossum965fdae2000-04-04 19:50:04 +0000422 return self.data[key.upper()]
Guido van Rossumc524d952001-10-19 01:31:59 +0000423 try:
424 unsetenv
425 except NameError:
426 def __delitem__(self, key):
427 del self.data[key.upper()]
428 else:
429 def __delitem__(self, key):
430 unsetenv(key)
431 del self.data[key.upper()]
Guido van Rossumb46413f1999-05-03 15:23:24 +0000432 def has_key(self, key):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000433 return key.upper() in self.data
434 def __contains__(self, key):
435 return key.upper() in self.data
Guido van Rossum965fdae2000-04-04 19:50:04 +0000436 def get(self, key, failobj=None):
437 return self.data.get(key.upper(), failobj)
Martin v. Löwisa066f462002-05-02 17:39:19 +0000438 def copy(self):
439 return dict(self)
Guido van Rossum3b8e20d1996-07-24 00:55:17 +0000440
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000441 else: # Where Env Var Names Can Be Mixed Case
Raymond Hettinger05212fc2002-09-07 04:48:03 +0000442 class _Environ(UserDict.IterableUserDict):
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000443 def __init__(self, environ):
444 UserDict.UserDict.__init__(self)
445 self.data = environ
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000446 def __setitem__(self, key, item):
447 putenv(key, item)
448 self.data[key] = item
Guido van Rossumc524d952001-10-19 01:31:59 +0000449 try:
450 unsetenv
451 except NameError:
452 pass
453 else:
454 def __delitem__(self, key):
455 unsetenv(key)
456 del self.data[key]
Martin v. Löwisa066f462002-05-02 17:39:19 +0000457 def copy(self):
458 return dict(self)
Tim Peters1633a2e2001-10-30 05:56:40 +0000459
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000460
461 environ = _Environ(environ)
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000462
Jack Jansenb11ce9b2003-01-08 16:33:40 +0000463def getenv(key, default=None):
Tim Peters2c60f7a2003-01-29 03:49:43 +0000464 """Get an environment variable, return None if it doesn't exist.
465 The optional second argument can specify an alternate default."""
466 return environ.get(key, default)
Jack Jansenb11ce9b2003-01-08 16:33:40 +0000467__all__.append("getenv")
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000468
469def _exists(name):
470 try:
471 eval(name)
Tim Petersbc0e9102002-04-04 22:55:58 +0000472 return True
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000473 except NameError:
Tim Petersbc0e9102002-04-04 22:55:58 +0000474 return False
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000475
476# Supply spawn*() (probably only for Unix)
477if _exists("fork") and not _exists("spawnv") and _exists("execv"):
478
479 P_WAIT = 0
480 P_NOWAIT = P_NOWAITO = 1
481
482 # XXX Should we support P_DETACH? I suppose it could fork()**2
483 # and close the std I/O streams. Also, P_OVERLAY is the same
484 # as execv*()?
485
486 def _spawnvef(mode, file, args, env, func):
487 # Internal helper; func is the exec*() function to use
488 pid = fork()
489 if not pid:
490 # Child
491 try:
492 if env is None:
493 func(file, args)
494 else:
495 func(file, args, env)
496 except:
497 _exit(127)
498 else:
499 # Parent
500 if mode == P_NOWAIT:
501 return pid # Caller is responsible for waiting!
502 while 1:
503 wpid, sts = waitpid(pid, 0)
504 if WIFSTOPPED(sts):
505 continue
506 elif WIFSIGNALED(sts):
507 return -WTERMSIG(sts)
508 elif WIFEXITED(sts):
509 return WEXITSTATUS(sts)
510 else:
511 raise error, "Not stopped, signaled or exited???"
512
513 def spawnv(mode, file, args):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000514 """spawnv(mode, file, args) -> integer
515
516Execute file with arguments from args in a subprocess.
517If mode == P_NOWAIT return the pid of the process.
518If mode == P_WAIT return the process's exit code if it exits normally;
Tim Peters2344fae2001-01-15 00:50:52 +0000519otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000520 return _spawnvef(mode, file, args, None, execv)
521
522 def spawnve(mode, file, args, env):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000523 """spawnve(mode, file, args, env) -> integer
524
525Execute file with arguments from args in a subprocess with the
526specified environment.
527If mode == P_NOWAIT return the pid of the process.
528If mode == P_WAIT return the process's exit code if it exits normally;
529otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000530 return _spawnvef(mode, file, args, env, execve)
531
Guido van Rossumdd7cbbf1999-11-02 20:44:07 +0000532 # Note: spawnvp[e] is't currently supported on Windows
533
534 def spawnvp(mode, file, args):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000535 """spawnvp(mode, file, args) -> integer
536
537Execute file (which is looked for along $PATH) with arguments from
538args in a subprocess.
539If mode == P_NOWAIT return the pid of the process.
540If mode == P_WAIT return the process's exit code if it exits normally;
541otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossumdd7cbbf1999-11-02 20:44:07 +0000542 return _spawnvef(mode, file, args, None, execvp)
543
544 def spawnvpe(mode, file, args, env):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000545 """spawnvpe(mode, file, args, env) -> integer
546
547Execute file (which is looked for along $PATH) with arguments from
548args in a subprocess with the supplied environment.
549If mode == P_NOWAIT return the pid of the process.
550If mode == P_WAIT return the process's exit code if it exits normally;
551otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossumdd7cbbf1999-11-02 20:44:07 +0000552 return _spawnvef(mode, file, args, env, execvpe)
553
554if _exists("spawnv"):
555 # These aren't supplied by the basic Windows code
556 # but can be easily implemented in Python
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000557
558 def spawnl(mode, file, *args):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000559 """spawnl(mode, file, *args) -> integer
560
561Execute file with arguments from args in a subprocess.
562If mode == P_NOWAIT return the pid of the process.
563If mode == P_WAIT return the process's exit code if it exits normally;
564otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000565 return spawnv(mode, file, args)
566
567 def spawnle(mode, file, *args):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000568 """spawnle(mode, file, *args, env) -> integer
569
570Execute file with arguments from args in a subprocess with the
571supplied environment.
572If mode == P_NOWAIT return the pid of the process.
573If mode == P_WAIT return the process's exit code if it exits normally;
574otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000575 env = args[-1]
576 return spawnve(mode, file, args[:-1], env)
577
Andrew MacIntyre69e18c92004-04-04 07:11:43 +0000578
579 __all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",])
580
581
Guido van Rossumdd7cbbf1999-11-02 20:44:07 +0000582if _exists("spawnvp"):
583 # At the moment, Windows doesn't implement spawnvp[e],
584 # so it won't have spawnlp[e] either.
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000585 def spawnlp(mode, file, *args):
Neal Norwitzb7f68102003-07-02 02:49:33 +0000586 """spawnlp(mode, file, *args) -> integer
Guido van Rossume0cd2912000-04-21 18:35:36 +0000587
588Execute file (which is looked for along $PATH) with arguments from
589args in a subprocess with the supplied environment.
590If mode == P_NOWAIT return the pid of the process.
591If mode == P_WAIT return the process's exit code if it exits normally;
592otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000593 return spawnvp(mode, file, args)
594
595 def spawnlpe(mode, file, *args):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000596 """spawnlpe(mode, file, *args, env) -> integer
597
598Execute file (which is looked for along $PATH) with arguments from
599args in a subprocess with the supplied environment.
600If mode == P_NOWAIT return the pid of the process.
601If mode == P_WAIT return the process's exit code if it exits normally;
602otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000603 env = args[-1]
604 return spawnvpe(mode, file, args[:-1], env)
Guido van Rossume0cd2912000-04-21 18:35:36 +0000605
606
Andrew MacIntyre69e18c92004-04-04 07:11:43 +0000607 __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",])
Skip Montanaro269b83b2001-02-06 01:07:02 +0000608
609
Guido van Rossumd9a8e962000-09-19 03:04:52 +0000610# Supply popen2 etc. (for Unix)
611if _exists("fork"):
612 if not _exists("popen2"):
613 def popen2(cmd, mode="t", bufsize=-1):
Guido van Rossumd9a8e962000-09-19 03:04:52 +0000614 import popen2
615 stdout, stdin = popen2.popen2(cmd, bufsize)
616 return stdin, stdout
Skip Montanaro269b83b2001-02-06 01:07:02 +0000617 __all__.append("popen2")
Fred Drake31f182e2000-08-28 17:20:05 +0000618
Guido van Rossumd9a8e962000-09-19 03:04:52 +0000619 if not _exists("popen3"):
620 def popen3(cmd, mode="t", bufsize=-1):
Guido van Rossumd9a8e962000-09-19 03:04:52 +0000621 import popen2
622 stdout, stdin, stderr = popen2.popen3(cmd, bufsize)
623 return stdin, stdout, stderr
Skip Montanaro269b83b2001-02-06 01:07:02 +0000624 __all__.append("popen3")
Fred Drake20af3172000-09-28 19:10:56 +0000625
626 if not _exists("popen4"):
627 def popen4(cmd, mode="t", bufsize=-1):
628 import popen2
629 stdout, stdin = popen2.popen4(cmd, bufsize)
630 return stdin, stdout
Skip Montanaro269b83b2001-02-06 01:07:02 +0000631 __all__.append("popen4")
Michael W. Hudson0e025302002-03-06 17:11:18 +0000632
633import copy_reg as _copy_reg
634
635def _make_stat_result(tup, dict):
636 return stat_result(tup, dict)
637
638def _pickle_stat_result(sr):
639 (type, args) = sr.__reduce__()
640 return (_make_stat_result, args)
641
Michael W. Hudsonce00b732002-03-15 10:18:58 +0000642try:
643 _copy_reg.pickle(stat_result, _pickle_stat_result, _make_stat_result)
644except NameError: # stat_result may not exist
645 pass
Michael W. Hudson0e025302002-03-06 17:11:18 +0000646
647def _make_statvfs_result(tup, dict):
648 return statvfs_result(tup, dict)
649
650def _pickle_statvfs_result(sr):
651 (type, args) = sr.__reduce__()
652 return (_make_statvfs_result, args)
653
Michael W. Hudsonce00b732002-03-15 10:18:58 +0000654try:
655 _copy_reg.pickle(statvfs_result, _pickle_statvfs_result,
656 _make_statvfs_result)
Michael W. Hudsone5363b72002-03-15 10:21:59 +0000657except NameError: # statvfs_result may not exist
Michael W. Hudsonce00b732002-03-15 10:18:58 +0000658 pass