blob: 81e037af3cd4ee7188751236d9de2e120273803a [file] [log] [blame]
Georg Brandlbde4ad42006-01-20 21:36:02 +00001r"""OS routines for Mac, 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:
Alexandre Vassalottieca20b62008-05-16 02:54:33 +00004 - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.
5 - os.path is either posixpath or ntpath
6 - os.name is either 'posix', 'nt', 'os2' or 'ce'.
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 '\\')
Georg Brandled5b9b32008-12-05 07:45:54 +000010 - os.extsep is the extension separator (always '.')
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
Christian Heimes45f9af32007-11-27 21:50:00 +000026import sys, errno
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.
Brett Cannon13962fc2008-08-18 01:45:29 +000031__all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
Martin v. Löwis22b457e2005-01-16 08:40:58 +000032 "defpath", "name", "path", "devnull",
33 "SEEK_SET", "SEEK_CUR", "SEEK_END"]
Skip Montanaro269b83b2001-02-06 01:07:02 +000034
35def _get_exports_list(module):
36 try:
37 return list(module.__all__)
38 except AttributeError:
39 return [n for n in dir(module) if n[0] != '_']
40
Guido van Rossuma28dab51997-08-29 22:36:47 +000041if 'posix' in _names:
Guido van Rossum61de0ac1997-12-05 21:24:30 +000042 name = 'posix'
Guido van Rossume9387ea1998-05-22 15:26:04 +000043 linesep = '\n'
Guido van Rossum61de0ac1997-12-05 21:24:30 +000044 from posix import *
45 try:
46 from posix import _exit
47 except ImportError:
48 pass
Skip Montanaro117910d2003-02-14 19:35:31 +000049 import posixpath as path
Tim Petersf2715e02003-02-19 02:35:07 +000050
Skip Montanaro269b83b2001-02-06 01:07:02 +000051 import posix
52 __all__.extend(_get_exports_list(posix))
53 del posix
54
Guido van Rossuma28dab51997-08-29 22:36:47 +000055elif 'nt' in _names:
Guido van Rossum61de0ac1997-12-05 21:24:30 +000056 name = 'nt'
Guido van Rossume9387ea1998-05-22 15:26:04 +000057 linesep = '\r\n'
Guido van Rossum61de0ac1997-12-05 21:24:30 +000058 from nt import *
Tim Peters6757c1e2003-01-08 21:20:57 +000059 try:
60 from nt import _exit
61 except ImportError:
62 pass
Skip Montanaro117910d2003-02-14 19:35:31 +000063 import ntpath as path
Tim Petersf2715e02003-02-19 02:35:07 +000064
Skip Montanaro269b83b2001-02-06 01:07:02 +000065 import nt
66 __all__.extend(_get_exports_list(nt))
67 del nt
68
Guido van Rossum8e9ebfd1997-11-22 21:53:48 +000069elif 'os2' in _names:
Guido van Rossum61de0ac1997-12-05 21:24:30 +000070 name = 'os2'
Guido van Rossume9387ea1998-05-22 15:26:04 +000071 linesep = '\r\n'
Guido van Rossum61de0ac1997-12-05 21:24:30 +000072 from os2 import *
73 try:
74 from os2 import _exit
75 except ImportError:
76 pass
Andrew MacIntyre5cef5712002-02-24 05:32:32 +000077 if sys.version.find('EMX GCC') == -1:
Skip Montanaro117910d2003-02-14 19:35:31 +000078 import ntpath as path
Andrew MacIntyre5cef5712002-02-24 05:32:32 +000079 else:
Skip Montanaro117910d2003-02-14 19:35:31 +000080 import os2emxpath as path
Andrew MacIntyre89f98652003-12-02 12:33:01 +000081 from _emx_link import link
Tim Petersf2715e02003-02-19 02:35:07 +000082
Skip Montanaro269b83b2001-02-06 01:07:02 +000083 import os2
84 __all__.extend(_get_exports_list(os2))
85 del os2
86
Guido van Rossum18df5d41999-06-11 01:37:27 +000087elif 'ce' in _names:
88 name = 'ce'
89 linesep = '\r\n'
Guido van Rossum18df5d41999-06-11 01:37:27 +000090 from ce import *
Tim Peters6757c1e2003-01-08 21:20:57 +000091 try:
92 from ce import _exit
93 except ImportError:
94 pass
Guido van Rossum18df5d41999-06-11 01:37:27 +000095 # We can use the standard Windows path.
Skip Montanaro117910d2003-02-14 19:35:31 +000096 import ntpath as path
Tim Petersf2715e02003-02-19 02:35:07 +000097
Skip Montanaro269b83b2001-02-06 01:07:02 +000098 import ce
99 __all__.extend(_get_exports_list(ce))
100 del ce
101
Guido van Rossum2979b011994-08-01 11:18:30 +0000102else:
Collin Winter828f04a2007-08-31 00:04:24 +0000103 raise ImportError('no os specific module found')
Guido van Rossume65cce51993-11-08 15:05:21 +0000104
Skip Montanaro117910d2003-02-14 19:35:31 +0000105sys.modules['os.path'] = path
Georg Brandled5b9b32008-12-05 07:45:54 +0000106from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
107 devnull)
Skip Montanaro269b83b2001-02-06 01:07:02 +0000108
Guido van Rossuma28dab51997-08-29 22:36:47 +0000109del _names
110
Martin v. Löwis22b457e2005-01-16 08:40:58 +0000111# Python uses fixed values for the SEEK_ constants; they are mapped
112# to native constants if necessary in posixmodule.c
113SEEK_SET = 0
114SEEK_CUR = 1
115SEEK_END = 2
116
Terry Reedy5a22b652010-12-02 07:05:56 +0000117
118def _get_masked_mode(mode):
119 mask = umask(0)
120 umask(mask)
121 return mode & ~mask
122
Skip Montanaro269b83b2001-02-06 01:07:02 +0000123#'
124
Guido van Rossum4def7de1998-07-24 20:48:03 +0000125# Super directory utilities.
126# (Inspired by Eric Raymond; the doc strings are mostly his)
127
Terry Reedy5a22b652010-12-02 07:05:56 +0000128def makedirs(name, mode=0o777, exist_ok=False):
129 """makedirs(path [, mode=0o777][, exist_ok=False])
Guido van Rossum4def7de1998-07-24 20:48:03 +0000130
131 Super-mkdir; create a leaf directory and all intermediate ones.
132 Works like mkdir, except that any intermediate path segment (not
Terry Reedy5a22b652010-12-02 07:05:56 +0000133 just the rightmost) will be created if it does not exist. If the
134 target directory with the same mode as we specified already exists,
135 raises an OSError if exist_ok is False, otherwise no exception is
136 raised. This is recursive.
Guido van Rossum4def7de1998-07-24 20:48:03 +0000137
138 """
139 head, tail = path.split(name)
Fred Drake9f2550f2000-07-25 15:16:40 +0000140 if not tail:
141 head, tail = path.split(head)
Guido van Rossum4def7de1998-07-24 20:48:03 +0000142 if head and tail and not path.exists(head):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000143 try:
Terry Reedy5a22b652010-12-02 07:05:56 +0000144 makedirs(head, mode, exist_ok)
Guido van Rossumb940e112007-01-10 16:19:56 +0000145 except OSError as e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000146 # be happy if someone already created the path
Christian Heimes45f9af32007-11-27 21:50:00 +0000147 if e.errno != errno.EEXIST:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000148 raise
Serhiy Storchaka4ab23bf2013-01-08 11:32:58 +0200149 cdir = curdir
150 if isinstance(tail, bytes):
151 cdir = bytes(curdir, 'ASCII')
152 if tail == cdir: # xxx/newdir/. exists if xxx/newdir exists
Andrew M. Kuchling6fccc8a2003-12-23 16:33:28 +0000153 return
Terry Reedy5a22b652010-12-02 07:05:56 +0000154 try:
155 mkdir(name, mode)
156 except OSError as e:
157 import stat as st
Gregory P. Smitha81c8562012-06-03 14:30:44 -0700158 dir_exists = path.isdir(name)
159 expected_mode = _get_masked_mode(mode)
160 if dir_exists:
161 # S_ISGID is automatically copied by the OS from parent to child
162 # directories on mkdir. Don't consider it being set to be a mode
163 # mismatch as mkdir does not unset it when not specified in mode.
164 actual_mode = st.S_IMODE(lstat(name).st_mode) & ~st.S_ISGID
165 else:
166 actual_mode = -1
167 if not (e.errno == errno.EEXIST and exist_ok and dir_exists and
168 actual_mode == expected_mode):
Terry Reedy5a22b652010-12-02 07:05:56 +0000169 raise
Guido van Rossum4def7de1998-07-24 20:48:03 +0000170
171def removedirs(name):
Fred Drakecadb9eb2002-07-02 21:28:04 +0000172 """removedirs(path)
Guido van Rossum4def7de1998-07-24 20:48:03 +0000173
Fredrik Lundh96c1c7a2005-11-12 15:55:04 +0000174 Super-rmdir; remove a leaf directory and all empty intermediate
Guido van Rossum4def7de1998-07-24 20:48:03 +0000175 ones. Works like rmdir except that, if the leaf directory is
176 successfully removed, directories corresponding to rightmost path
Tim Petersc4e09402003-04-25 07:11:48 +0000177 segments will be pruned away until either the whole path is
Guido van Rossum4def7de1998-07-24 20:48:03 +0000178 consumed or an error occurs. Errors during this latter phase are
179 ignored -- they generally mean that a directory was not empty.
180
181 """
182 rmdir(name)
183 head, tail = path.split(name)
Fred Drake9f2550f2000-07-25 15:16:40 +0000184 if not tail:
185 head, tail = path.split(head)
Guido van Rossum4def7de1998-07-24 20:48:03 +0000186 while head and tail:
187 try:
188 rmdir(head)
189 except error:
190 break
191 head, tail = path.split(head)
192
193def renames(old, new):
Fred Drakecadb9eb2002-07-02 21:28:04 +0000194 """renames(old, new)
Guido van Rossum4def7de1998-07-24 20:48:03 +0000195
196 Super-rename; create directories as necessary and delete any left
197 empty. Works like rename, except creation of any intermediate
198 directories needed to make the new pathname good is attempted
199 first. After the rename, directories corresponding to rightmost
200 path segments of the old name will be pruned way until either the
201 whole path is consumed or a nonempty directory is found.
202
203 Note: this function can fail with the new directory structure made
204 if you lack permissions needed to unlink the leaf directory or
205 file.
206
207 """
208 head, tail = path.split(new)
209 if head and tail and not path.exists(head):
210 makedirs(head)
211 rename(old, new)
212 head, tail = path.split(old)
213 if head and tail:
214 try:
215 removedirs(head)
216 except error:
217 pass
218
Skip Montanaro269b83b2001-02-06 01:07:02 +0000219__all__.extend(["makedirs", "removedirs", "renames"])
220
Guido van Rossumd8faa362007-04-27 19:54:29 +0000221def walk(top, topdown=True, onerror=None, followlinks=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000222 """Directory tree generator.
223
224 For each directory in the directory tree rooted at top (including top
225 itself, but excluding '.' and '..'), yields a 3-tuple
226
227 dirpath, dirnames, filenames
228
229 dirpath is a string, the path to the directory. dirnames is a list of
230 the names of the subdirectories in dirpath (excluding '.' and '..').
231 filenames is a list of the names of the non-directory files in dirpath.
232 Note that the names in the lists are just names, with no path components.
233 To get a full path (which begins with top) to a file or directory in
234 dirpath, do os.path.join(dirpath, name).
235
236 If optional arg 'topdown' is true or not specified, the triple for a
237 directory is generated before the triples for any of its subdirectories
238 (directories are generated top down). If topdown is false, the triple
239 for a directory is generated after the triples for all of its
240 subdirectories (directories are generated bottom up).
241
242 When topdown is true, the caller can modify the dirnames list in-place
243 (e.g., via del or slice assignment), and walk will only recurse into the
244 subdirectories whose names remain in dirnames; this can be used to prune
245 the search, or to impose a specific order of visiting. Modifying
246 dirnames when topdown is false is ineffective, since the directories in
247 dirnames have already been generated by the time dirnames itself is
248 generated.
249
Guido van Rossumbf1bef82003-05-13 18:01:19 +0000250 By default errors from the os.listdir() call are ignored. If
251 optional arg 'onerror' is specified, it should be a function; it
252 will be called with one argument, an os.error instance. It can
253 report the error to continue with the walk, or raise the exception
254 to abort the walk. Note that the filename is available as the
255 filename attribute of the exception object.
256
Guido van Rossumd8faa362007-04-27 19:54:29 +0000257 By default, os.walk does not follow symbolic links to subdirectories on
258 systems that support them. In order to get this functionality, set the
259 optional argument 'followlinks' to true.
260
Tim Petersc4e09402003-04-25 07:11:48 +0000261 Caution: if you pass a relative pathname for top, don't change the
262 current working directory between resumptions of walk. walk never
263 changes the current directory, and assumes that the client doesn't
264 either.
265
266 Example:
267
Christian Heimes5d8da202008-05-06 13:58:24 +0000268 import os
Tim Petersc4e09402003-04-25 07:11:48 +0000269 from os.path import join, getsize
Christian Heimes5d8da202008-05-06 13:58:24 +0000270 for root, dirs, files in os.walk('python/Lib/email'):
Neal Norwitz752abd02008-05-13 04:55:24 +0000271 print(root, "consumes", end="")
272 print(sum([getsize(join(root, name)) for name in files]), end="")
273 print("bytes in", len(files), "non-directory files")
Tim Petersc4e09402003-04-25 07:11:48 +0000274 if 'CVS' in dirs:
275 dirs.remove('CVS') # don't visit CVS directories
276 """
277
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000278 islink, join, isdir = path.islink, path.join, path.isdir
Tim Petersc4e09402003-04-25 07:11:48 +0000279
280 # We may not have read permission for top, in which case we can't
Alexandre Vassalotti4e6531e2008-05-09 20:00:17 +0000281 # get a list of the files the directory contains. os.walk
Tim Petersc4e09402003-04-25 07:11:48 +0000282 # always suppressed the exception then, rather than blow up for a
283 # minor reason when (say) a thousand readable directories are still
284 # left to visit. That logic is copied here.
285 try:
286 # Note that listdir and error are globals in this module due
287 # to earlier import-*.
288 names = listdir(top)
Guido van Rossumb940e112007-01-10 16:19:56 +0000289 except error as err:
Guido van Rossumbf1bef82003-05-13 18:01:19 +0000290 if onerror is not None:
291 onerror(err)
Tim Petersc4e09402003-04-25 07:11:48 +0000292 return
293
294 dirs, nondirs = [], []
295 for name in names:
296 if isdir(join(top, name)):
297 dirs.append(name)
298 else:
299 nondirs.append(name)
300
301 if topdown:
302 yield top, dirs, nondirs
303 for name in dirs:
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000304 new_path = join(top, name)
305 if followlinks or not islink(new_path):
306 for x in walk(new_path, topdown, onerror, followlinks):
Tim Petersc4e09402003-04-25 07:11:48 +0000307 yield x
308 if not topdown:
309 yield top, dirs, nondirs
310
311__all__.append("walk")
312
Guido van Rossuma28dab51997-08-29 22:36:47 +0000313# Make sure os.environ exists, at least
314try:
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000315 environ
Guido van Rossuma28dab51997-08-29 22:36:47 +0000316except NameError:
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000317 environ = {}
Guido van Rossuma28dab51997-08-29 22:36:47 +0000318
Guido van Rossume65cce51993-11-08 15:05:21 +0000319def execl(file, *args):
Guido van Rossum7da3cc52000-04-25 10:53:22 +0000320 """execl(file, *args)
321
322 Execute the executable file with argument list args, replacing the
323 current process. """
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000324 execv(file, args)
Guido van Rossume65cce51993-11-08 15:05:21 +0000325
326def execle(file, *args):
Guido van Rossum7da3cc52000-04-25 10:53:22 +0000327 """execle(file, *args, env)
328
329 Execute the executable file with argument list args and
330 environment env, replacing the current process. """
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000331 env = args[-1]
332 execve(file, args[:-1], env)
Guido van Rossume65cce51993-11-08 15:05:21 +0000333
334def execlp(file, *args):
Guido van Rossum7da3cc52000-04-25 10:53:22 +0000335 """execlp(file, *args)
336
337 Execute the executable file (which is searched for along $PATH)
338 with argument list args, replacing the current process. """
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000339 execvp(file, args)
Guido van Rossume65cce51993-11-08 15:05:21 +0000340
Guido van Rossum030afb11995-03-14 17:27:18 +0000341def execlpe(file, *args):
Guido van Rossum7da3cc52000-04-25 10:53:22 +0000342 """execlpe(file, *args, env)
343
344 Execute the executable file (which is searched for along $PATH)
345 with argument list args and environment env, replacing the current
Tim Peters2344fae2001-01-15 00:50:52 +0000346 process. """
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000347 env = args[-1]
348 execvpe(file, args[:-1], env)
Guido van Rossum030afb11995-03-14 17:27:18 +0000349
Guido van Rossume65cce51993-11-08 15:05:21 +0000350def execvp(file, args):
Matthias Klosea09c54f2010-01-31 16:48:44 +0000351 """execvp(file, args)
Guido van Rossum7da3cc52000-04-25 10:53:22 +0000352
353 Execute the executable file (which is searched for along $PATH)
354 with argument list args, replacing the current process.
Thomas Wouters7e474022000-07-16 12:04:32 +0000355 args may be a list or tuple of strings. """
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000356 _execvpe(file, args)
Guido van Rossum030afb11995-03-14 17:27:18 +0000357
358def execvpe(file, args, env):
Guido van Rossum683c0fe2002-09-03 16:36:17 +0000359 """execvpe(file, args, env)
Guido van Rossum7da3cc52000-04-25 10:53:22 +0000360
361 Execute the executable file (which is searched for along $PATH)
362 with argument list args and environment env , replacing the
363 current process.
Tim Peters2344fae2001-01-15 00:50:52 +0000364 args may be a list or tuple of strings. """
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000365 _execvpe(file, args, env)
Guido van Rossum030afb11995-03-14 17:27:18 +0000366
Skip Montanaro269b83b2001-02-06 01:07:02 +0000367__all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])
368
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000369def _execvpe(file, args, env=None):
370 if env is not None:
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000371 exec_func = execve
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000372 argrest = (args, env)
373 else:
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000374 exec_func = execv
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000375 argrest = (args,)
376 env = environ
Guido van Rossumaed51d82002-08-05 16:13:24 +0000377
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000378 head, tail = path.split(file)
379 if head:
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000380 exec_func(file, *argrest)
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000381 return
Guido van Rossume7ba4952007-06-06 23:52:48 +0000382 last_exc = saved_exc = None
Guido van Rossum683c0fe2002-09-03 16:36:17 +0000383 saved_tb = None
Victor Stinnerb745a742010-05-18 17:17:23 +0000384 path_list = get_exec_path(env)
385 if name != 'nt':
386 file = fsencode(file)
387 path_list = map(fsencode, path_list)
388 for dir in path_list:
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000389 fullname = path.join(dir, file)
390 try:
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000391 exec_func(fullname, *argrest)
Guido van Rossumb940e112007-01-10 16:19:56 +0000392 except error as e:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000393 last_exc = e
Guido van Rossum683c0fe2002-09-03 16:36:17 +0000394 tb = sys.exc_info()[2]
Christian Heimes45f9af32007-11-27 21:50:00 +0000395 if (e.errno != errno.ENOENT and e.errno != errno.ENOTDIR
Guido van Rossum683c0fe2002-09-03 16:36:17 +0000396 and saved_exc is None):
397 saved_exc = e
398 saved_tb = tb
399 if saved_exc:
Benjamin Peterson4b068192009-02-20 03:19:25 +0000400 raise saved_exc.with_traceback(saved_tb)
401 raise last_exc.with_traceback(tb)
Guido van Rossumd74fb6b2001-03-02 06:43:49 +0000402
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000403
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000404def get_exec_path(env=None):
405 """Returns the sequence of directories that will be searched for the
406 named executable (similar to a shell) when launching a process.
407
408 *env* must be an environment variable dict or None. If *env* is None,
409 os.environ will be used.
410 """
Victor Stinner273b7662010-11-06 12:59:33 +0000411 # Use a local import instead of a global import to limit the number of
412 # modules loaded at startup: the os module is always loaded at startup by
413 # Python. It may also avoid a bootstrap issue.
Victor Stinner6f35eda2010-10-29 00:38:58 +0000414 import warnings
415
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000416 if env is None:
417 env = environ
Victor Stinnerb745a742010-05-18 17:17:23 +0000418
Victor Stinnerbb4f2182010-11-07 15:43:39 +0000419 # {b'PATH': ...}.get('PATH') and {'PATH': ...}.get(b'PATH') emit a
420 # BytesWarning when using python -b or python -bb: ignore the warning
Victor Stinner273b7662010-11-06 12:59:33 +0000421 with warnings.catch_warnings():
422 warnings.simplefilter("ignore", BytesWarning)
Victor Stinnerb745a742010-05-18 17:17:23 +0000423
Victor Stinnerb745a742010-05-18 17:17:23 +0000424 try:
Victor Stinner273b7662010-11-06 12:59:33 +0000425 path_list = env.get('PATH')
426 except TypeError:
427 path_list = None
Victor Stinnerb745a742010-05-18 17:17:23 +0000428
Victor Stinner273b7662010-11-06 12:59:33 +0000429 if supports_bytes_environ:
430 try:
431 path_listb = env[b'PATH']
432 except (KeyError, TypeError):
433 pass
434 else:
435 if path_list is not None:
436 raise ValueError(
437 "env cannot contain 'PATH' and b'PATH' keys")
438 path_list = path_listb
439
440 if path_list is not None and isinstance(path_list, bytes):
441 path_list = fsdecode(path_list)
Victor Stinnerb745a742010-05-18 17:17:23 +0000442
443 if path_list is None:
444 path_list = defpath
445 return path_list.split(pathsep)
Gregory P. Smithb6e8c7e2010-02-27 07:22:22 +0000446
447
Skip Montanaro289bc052007-08-17 02:30:27 +0000448# Change environ to automatically call putenv(), unsetenv if they exist.
449from _abcoll import MutableMapping # Can't use collections (bootstrap)
450
451class _Environ(MutableMapping):
Victor Stinner84ae1182010-05-06 22:05:07 +0000452 def __init__(self, data, encodekey, decodekey, encodevalue, decodevalue, putenv, unsetenv):
453 self.encodekey = encodekey
454 self.decodekey = decodekey
455 self.encodevalue = encodevalue
456 self.decodevalue = decodevalue
Skip Montanaro289bc052007-08-17 02:30:27 +0000457 self.putenv = putenv
458 self.unsetenv = unsetenv
Victor Stinner3d75d0c2010-09-10 22:18:16 +0000459 self._data = data
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000460
Skip Montanaro289bc052007-08-17 02:30:27 +0000461 def __getitem__(self, key):
Victor Stinner3d75d0c2010-09-10 22:18:16 +0000462 value = self._data[self.encodekey(key)]
Victor Stinner84ae1182010-05-06 22:05:07 +0000463 return self.decodevalue(value)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000464
Skip Montanaro289bc052007-08-17 02:30:27 +0000465 def __setitem__(self, key, value):
Victor Stinner84ae1182010-05-06 22:05:07 +0000466 key = self.encodekey(key)
467 value = self.encodevalue(value)
Skip Montanaro289bc052007-08-17 02:30:27 +0000468 self.putenv(key, value)
Victor Stinner3d75d0c2010-09-10 22:18:16 +0000469 self._data[key] = value
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000470
Skip Montanaro289bc052007-08-17 02:30:27 +0000471 def __delitem__(self, key):
Victor Stinner84ae1182010-05-06 22:05:07 +0000472 key = self.encodekey(key)
Skip Montanaro289bc052007-08-17 02:30:27 +0000473 self.unsetenv(key)
Victor Stinner3d75d0c2010-09-10 22:18:16 +0000474 del self._data[key]
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000475
Skip Montanaro289bc052007-08-17 02:30:27 +0000476 def __iter__(self):
Victor Stinner3d75d0c2010-09-10 22:18:16 +0000477 for key in self._data:
Victor Stinner84ae1182010-05-06 22:05:07 +0000478 yield self.decodekey(key)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000479
Skip Montanaro289bc052007-08-17 02:30:27 +0000480 def __len__(self):
Victor Stinner3d75d0c2010-09-10 22:18:16 +0000481 return len(self._data)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000482
483 def __repr__(self):
Victor Stinnerbed71172010-07-28 21:25:42 +0000484 return 'environ({{{}}})'.format(', '.join(
Victor Stinnerd73c1a32010-07-28 21:23:23 +0000485 ('{!r}: {!r}'.format(self.decodekey(key), self.decodevalue(value))
Victor Stinner3d75d0c2010-09-10 22:18:16 +0000486 for key, value in self._data.items())))
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000487
Skip Montanaro289bc052007-08-17 02:30:27 +0000488 def copy(self):
489 return dict(self)
Ezio Melotti19e4acf2010-02-22 15:59:01 +0000490
Skip Montanaro289bc052007-08-17 02:30:27 +0000491 def setdefault(self, key, value):
492 if key not in self:
493 self[key] = value
494 return self[key]
495
496try:
497 _putenv = putenv
498except NameError:
499 _putenv = lambda key, value: None
Martin v. Löwisa90f4382001-03-07 09:05:45 +0000500else:
Skip Montanaro289bc052007-08-17 02:30:27 +0000501 __all__.append("putenv")
Guido van Rossum3b8e20d1996-07-24 00:55:17 +0000502
Skip Montanaro289bc052007-08-17 02:30:27 +0000503try:
504 _unsetenv = unsetenv
505except NameError:
506 _unsetenv = lambda key: _putenv(key, "")
507else:
508 __all__.append("unsetenv")
Guido van Rossumc524d952001-10-19 01:31:59 +0000509
Victor Stinner84ae1182010-05-06 22:05:07 +0000510def _createenviron():
511 if name in ('os2', 'nt'):
512 # Where Env Var Names Must Be UPPERCASE
513 def check_str(value):
514 if not isinstance(value, str):
515 raise TypeError("str expected, not %s" % type(value).__name__)
516 return value
517 encode = check_str
518 decode = str
519 def encodekey(key):
520 return encode(key).upper()
521 data = {}
522 for key, value in environ.items():
523 data[encodekey(key)] = value
524 else:
525 # Where Env Var Names Can Be Mixed Case
Victor Stinnerdf6d6cb2010-10-24 20:32:26 +0000526 encoding = sys.getfilesystemencoding()
Victor Stinner84ae1182010-05-06 22:05:07 +0000527 def encode(value):
528 if not isinstance(value, str):
529 raise TypeError("str expected, not %s" % type(value).__name__)
Victor Stinnerdf6d6cb2010-10-24 20:32:26 +0000530 return value.encode(encoding, 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000531 def decode(value):
Victor Stinnerdf6d6cb2010-10-24 20:32:26 +0000532 return value.decode(encoding, 'surrogateescape')
Victor Stinner84ae1182010-05-06 22:05:07 +0000533 encodekey = encode
534 data = environ
535 return _Environ(data,
536 encodekey, decode,
537 encode, decode,
538 _putenv, _unsetenv)
Guido van Rossumc524d952001-10-19 01:31:59 +0000539
Victor Stinner84ae1182010-05-06 22:05:07 +0000540# unicode environ
541environ = _createenviron()
542del _createenviron
Guido van Rossum61de0ac1997-12-05 21:24:30 +0000543
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000544
Jack Jansenb11ce9b2003-01-08 16:33:40 +0000545def getenv(key, default=None):
Tim Peters2c60f7a2003-01-29 03:49:43 +0000546 """Get an environment variable, return None if it doesn't exist.
Victor Stinner84ae1182010-05-06 22:05:07 +0000547 The optional second argument can specify an alternate default.
548 key, default and the result are str."""
Tim Peters2c60f7a2003-01-29 03:49:43 +0000549 return environ.get(key, default)
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000550
Victor Stinnerb745a742010-05-18 17:17:23 +0000551supports_bytes_environ = name not in ('os2', 'nt')
552__all__.extend(("getenv", "supports_bytes_environ"))
553
554if supports_bytes_environ:
Victor Stinner84ae1182010-05-06 22:05:07 +0000555 def _check_bytes(value):
556 if not isinstance(value, bytes):
557 raise TypeError("bytes expected, not %s" % type(value).__name__)
558 return value
559
560 # bytes environ
Victor Stinner3d75d0c2010-09-10 22:18:16 +0000561 environb = _Environ(environ._data,
Victor Stinner84ae1182010-05-06 22:05:07 +0000562 _check_bytes, bytes,
563 _check_bytes, bytes,
564 _putenv, _unsetenv)
565 del _check_bytes
566
567 def getenvb(key, default=None):
568 """Get an environment variable, return None if it doesn't exist.
569 The optional second argument can specify an alternate default.
570 key, default and the result are bytes."""
571 return environb.get(key, default)
Victor Stinner70120e22010-07-29 17:19:38 +0000572
573 __all__.extend(("environb", "getenvb"))
Victor Stinner84ae1182010-05-06 22:05:07 +0000574
Victor Stinnerdf6d6cb2010-10-24 20:32:26 +0000575def _fscodec():
576 encoding = sys.getfilesystemencoding()
577 if encoding == 'mbcs':
Victor Stinnere882aac2010-10-24 21:12:26 +0000578 errors = 'strict'
Victor Stinner313a1202010-06-11 23:56:51 +0000579 else:
Victor Stinnerdf6d6cb2010-10-24 20:32:26 +0000580 errors = 'surrogateescape'
Victor Stinnere8d51452010-08-19 01:05:19 +0000581
Victor Stinnerdf6d6cb2010-10-24 20:32:26 +0000582 def fsencode(filename):
583 """
584 Encode filename to the filesystem encoding with 'surrogateescape' error
585 handler, return bytes unchanged. On Windows, use 'strict' error handler if
586 the file system encoding is 'mbcs' (which is the default encoding).
587 """
588 if isinstance(filename, bytes):
589 return filename
590 elif isinstance(filename, str):
591 return filename.encode(encoding, errors)
Victor Stinnere8d51452010-08-19 01:05:19 +0000592 else:
Victor Stinnerdf6d6cb2010-10-24 20:32:26 +0000593 raise TypeError("expect bytes or str, not %s" % type(filename).__name__)
594
595 def fsdecode(filename):
596 """
597 Decode filename from the filesystem encoding with 'surrogateescape' error
598 handler, return str unchanged. On Windows, use 'strict' error handler if
599 the file system encoding is 'mbcs' (which is the default encoding).
600 """
601 if isinstance(filename, str):
602 return filename
603 elif isinstance(filename, bytes):
604 return filename.decode(encoding, errors)
605 else:
606 raise TypeError("expect bytes or str, not %s" % type(filename).__name__)
607
608 return fsencode, fsdecode
609
610fsencode, fsdecode = _fscodec()
611del _fscodec
Victor Stinner449c4662010-05-08 11:10:09 +0000612
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000613def _exists(name):
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000614 return name in globals()
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000615
616# Supply spawn*() (probably only for Unix)
617if _exists("fork") and not _exists("spawnv") and _exists("execv"):
618
619 P_WAIT = 0
620 P_NOWAIT = P_NOWAITO = 1
621
622 # XXX Should we support P_DETACH? I suppose it could fork()**2
623 # and close the std I/O streams. Also, P_OVERLAY is the same
624 # as execv*()?
625
626 def _spawnvef(mode, file, args, env, func):
627 # Internal helper; func is the exec*() function to use
628 pid = fork()
629 if not pid:
630 # Child
631 try:
632 if env is None:
633 func(file, args)
634 else:
635 func(file, args, env)
636 except:
637 _exit(127)
638 else:
639 # Parent
640 if mode == P_NOWAIT:
641 return pid # Caller is responsible for waiting!
642 while 1:
643 wpid, sts = waitpid(pid, 0)
644 if WIFSTOPPED(sts):
645 continue
646 elif WIFSIGNALED(sts):
647 return -WTERMSIG(sts)
648 elif WIFEXITED(sts):
649 return WEXITSTATUS(sts)
650 else:
Collin Winter828f04a2007-08-31 00:04:24 +0000651 raise error("Not stopped, signaled or exited???")
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000652
653 def spawnv(mode, file, args):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000654 """spawnv(mode, file, args) -> integer
655
656Execute file with arguments from args in a subprocess.
657If mode == P_NOWAIT return the pid of the process.
658If mode == P_WAIT return the process's exit code if it exits normally;
Tim Peters2344fae2001-01-15 00:50:52 +0000659otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000660 return _spawnvef(mode, file, args, None, execv)
661
662 def spawnve(mode, file, args, env):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000663 """spawnve(mode, file, args, env) -> integer
664
665Execute file with arguments from args in a subprocess with the
666specified environment.
667If mode == P_NOWAIT return the pid of the process.
668If mode == P_WAIT return the process's exit code if it exits normally;
669otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000670 return _spawnvef(mode, file, args, env, execve)
671
Guido van Rossumdd7cbbf1999-11-02 20:44:07 +0000672 # Note: spawnvp[e] is't currently supported on Windows
673
674 def spawnvp(mode, file, args):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000675 """spawnvp(mode, file, args) -> integer
676
677Execute file (which is looked for along $PATH) with arguments from
678args in a subprocess.
679If mode == P_NOWAIT return the pid of the process.
680If mode == P_WAIT return the process's exit code if it exits normally;
681otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossumdd7cbbf1999-11-02 20:44:07 +0000682 return _spawnvef(mode, file, args, None, execvp)
683
684 def spawnvpe(mode, file, args, env):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000685 """spawnvpe(mode, file, args, env) -> integer
686
687Execute file (which is looked for along $PATH) with arguments from
688args in a subprocess with the supplied environment.
689If mode == P_NOWAIT return the pid of the process.
690If mode == P_WAIT return the process's exit code if it exits normally;
691otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossumdd7cbbf1999-11-02 20:44:07 +0000692 return _spawnvef(mode, file, args, env, execvpe)
693
694if _exists("spawnv"):
695 # These aren't supplied by the basic Windows code
696 # but can be easily implemented in Python
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000697
698 def spawnl(mode, file, *args):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000699 """spawnl(mode, file, *args) -> integer
700
701Execute file with arguments from args in a subprocess.
702If mode == P_NOWAIT return the pid of the process.
703If mode == P_WAIT return the process's exit code if it exits normally;
704otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000705 return spawnv(mode, file, args)
706
707 def spawnle(mode, file, *args):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000708 """spawnle(mode, file, *args, env) -> integer
709
710Execute file with arguments from args in a subprocess with the
711supplied environment.
712If mode == P_NOWAIT return the pid of the process.
713If mode == P_WAIT return the process's exit code if it exits normally;
714otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000715 env = args[-1]
716 return spawnve(mode, file, args[:-1], env)
717
Andrew MacIntyre69e18c92004-04-04 07:11:43 +0000718
719 __all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",])
720
721
Guido van Rossumdd7cbbf1999-11-02 20:44:07 +0000722if _exists("spawnvp"):
723 # At the moment, Windows doesn't implement spawnvp[e],
724 # so it won't have spawnlp[e] either.
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000725 def spawnlp(mode, file, *args):
Neal Norwitzb7f68102003-07-02 02:49:33 +0000726 """spawnlp(mode, file, *args) -> integer
Guido van Rossume0cd2912000-04-21 18:35:36 +0000727
728Execute file (which is looked for along $PATH) with arguments from
729args in a subprocess with the supplied environment.
730If mode == P_NOWAIT return the pid of the process.
731If mode == P_WAIT return the process's exit code if it exits normally;
732otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000733 return spawnvp(mode, file, args)
734
735 def spawnlpe(mode, file, *args):
Guido van Rossume0cd2912000-04-21 18:35:36 +0000736 """spawnlpe(mode, file, *args, env) -> integer
737
738Execute file (which is looked for along $PATH) with arguments from
739args in a subprocess with the supplied environment.
740If mode == P_NOWAIT return the pid of the process.
741If mode == P_WAIT return the process's exit code if it exits normally;
742otherwise return -SIG, where SIG is the signal that killed it. """
Guido van Rossum5a2ca931999-11-02 13:27:32 +0000743 env = args[-1]
744 return spawnvpe(mode, file, args[:-1], env)
Guido van Rossume0cd2912000-04-21 18:35:36 +0000745
746
Andrew MacIntyre69e18c92004-04-04 07:11:43 +0000747 __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",])
Skip Montanaro269b83b2001-02-06 01:07:02 +0000748
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000749import copyreg as _copyreg
Michael W. Hudson0e025302002-03-06 17:11:18 +0000750
751def _make_stat_result(tup, dict):
752 return stat_result(tup, dict)
753
754def _pickle_stat_result(sr):
755 (type, args) = sr.__reduce__()
756 return (_make_stat_result, args)
757
Michael W. Hudsonce00b732002-03-15 10:18:58 +0000758try:
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000759 _copyreg.pickle(stat_result, _pickle_stat_result, _make_stat_result)
Michael W. Hudsonce00b732002-03-15 10:18:58 +0000760except NameError: # stat_result may not exist
761 pass
Michael W. Hudson0e025302002-03-06 17:11:18 +0000762
763def _make_statvfs_result(tup, dict):
764 return statvfs_result(tup, dict)
765
766def _pickle_statvfs_result(sr):
767 (type, args) = sr.__reduce__()
768 return (_make_statvfs_result, args)
769
Michael W. Hudsonce00b732002-03-15 10:18:58 +0000770try:
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000771 _copyreg.pickle(statvfs_result, _pickle_statvfs_result,
Michael W. Hudsonce00b732002-03-15 10:18:58 +0000772 _make_statvfs_result)
Michael W. Hudsone5363b72002-03-15 10:21:59 +0000773except NameError: # statvfs_result may not exist
Michael W. Hudsonce00b732002-03-15 10:18:58 +0000774 pass
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000775
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000776# Supply os.popen()
Antoine Pitrou877766d2011-03-19 17:00:37 +0100777def popen(cmd, mode="r", buffering=-1):
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000778 if not isinstance(cmd, str):
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000779 raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
780 if mode not in ("r", "w"):
781 raise ValueError("invalid mode %r" % mode)
Antoine Pitrou877766d2011-03-19 17:00:37 +0100782 if buffering == 0 or buffering == None:
783 raise ValueError("popen() does not support unbuffered streams")
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000784 import subprocess, io
785 if mode == "r":
786 proc = subprocess.Popen(cmd,
787 shell=True,
788 stdout=subprocess.PIPE,
789 bufsize=buffering)
790 return _wrap_close(io.TextIOWrapper(proc.stdout), proc)
791 else:
792 proc = subprocess.Popen(cmd,
793 shell=True,
794 stdin=subprocess.PIPE,
795 bufsize=buffering)
796 return _wrap_close(io.TextIOWrapper(proc.stdin), proc)
797
798# Helper for popen() -- a proxy for a file whose close waits for the process
799class _wrap_close:
800 def __init__(self, stream, proc):
801 self._stream = stream
802 self._proc = proc
803 def close(self):
804 self._stream.close()
Amaury Forgeot d'Arc97e5f282009-07-11 09:35:13 +0000805 returncode = self._proc.wait()
806 if returncode == 0:
807 return None
808 if name == 'nt':
809 return returncode
810 else:
811 return returncode << 8 # Shift left to match old behavior
Antoine Pitrouac625352009-12-09 00:01:27 +0000812 def __enter__(self):
813 return self
814 def __exit__(self, *args):
815 self.close()
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000816 def __getattr__(self, name):
817 return getattr(self._stream, name)
Thomas Heller476157b2007-09-04 11:27:47 +0000818 def __iter__(self):
819 return iter(self._stream)
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000820
Amaury Forgeot d'Arcbdbddf82008-08-01 00:06:49 +0000821# Supply os.fdopen()
822def fdopen(fd, *args, **kwargs):
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000823 if not isinstance(fd, int):
824 raise TypeError("invalid fd type (%s, expected integer)" % type(fd))
825 import io
Amaury Forgeot d'Arcbdbddf82008-08-01 00:06:49 +0000826 return io.open(fd, *args, **kwargs)