os.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. r"""OS routines for NT or Posix depending on what system we're on.
  2. This exports:
  3. - all functions from posix or nt, e.g. unlink, stat, etc.
  4. - os.path is either posixpath or ntpath
  5. - os.name is either 'posix' or 'nt'
  6. - os.curdir is a string representing the current directory (always '.')
  7. - os.pardir is a string representing the parent directory (always '..')
  8. - os.sep is the (or a most common) pathname separator ('/' or '\\')
  9. - os.extsep is the extension separator (always '.')
  10. - os.altsep is the alternate pathname separator (None or '/')
  11. - os.pathsep is the component separator used in $PATH etc
  12. - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  13. - os.defpath is the default search path for executables
  14. - os.devnull is the file path of the null device ('/dev/null', etc.)
  15. Programs that import and use 'os' stand a better chance of being
  16. portable between different platforms. Of course, they must then
  17. only use functions that are defined by all platforms (e.g., unlink
  18. and opendir), and leave all pathname manipulation to os.path
  19. (e.g., split and join).
  20. """
  21. #'
  22. import abc
  23. import sys
  24. import stat as st
  25. from _collections_abc import _check_methods
  26. GenericAlias = type(list[int])
  27. _names = sys.builtin_module_names
  28. # Note: more names are added to __all__ later.
  29. __all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
  30. "defpath", "name", "path", "devnull", "SEEK_SET", "SEEK_CUR",
  31. "SEEK_END", "fsencode", "fsdecode", "get_exec_path", "fdopen",
  32. "popen", "extsep"]
  33. def _exists(name):
  34. return name in globals()
  35. def _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. # Any new dependencies of the os module and/or changes in path separator
  41. # requires updating importlib as well.
  42. if 'posix' in _names:
  43. name = 'posix'
  44. linesep = '\n'
  45. from posix import *
  46. try:
  47. from posix import _exit
  48. __all__.append('_exit')
  49. except ImportError:
  50. pass
  51. import posixpath as path
  52. try:
  53. from posix import _have_functions
  54. except ImportError:
  55. pass
  56. import posix
  57. __all__.extend(_get_exports_list(posix))
  58. del posix
  59. elif 'nt' in _names:
  60. name = 'nt'
  61. linesep = '\r\n'
  62. from nt import *
  63. try:
  64. from nt import _exit
  65. __all__.append('_exit')
  66. except ImportError:
  67. pass
  68. import ntpath as path
  69. import nt
  70. __all__.extend(_get_exports_list(nt))
  71. del nt
  72. try:
  73. from nt import _have_functions
  74. except ImportError:
  75. pass
  76. else:
  77. raise ImportError('no os specific module found')
  78. sys.modules['os.path'] = path
  79. from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
  80. devnull)
  81. del _names
  82. if _exists("_have_functions"):
  83. _globals = globals()
  84. def _add(str, fn):
  85. if (fn in _globals) and (str in _have_functions):
  86. _set.add(_globals[fn])
  87. _set = set()
  88. _add("HAVE_FACCESSAT", "access")
  89. _add("HAVE_FCHMODAT", "chmod")
  90. _add("HAVE_FCHOWNAT", "chown")
  91. _add("HAVE_FSTATAT", "stat")
  92. _add("HAVE_FUTIMESAT", "utime")
  93. _add("HAVE_LINKAT", "link")
  94. _add("HAVE_MKDIRAT", "mkdir")
  95. _add("HAVE_MKFIFOAT", "mkfifo")
  96. _add("HAVE_MKNODAT", "mknod")
  97. _add("HAVE_OPENAT", "open")
  98. _add("HAVE_READLINKAT", "readlink")
  99. _add("HAVE_RENAMEAT", "rename")
  100. _add("HAVE_SYMLINKAT", "symlink")
  101. _add("HAVE_UNLINKAT", "unlink")
  102. _add("HAVE_UNLINKAT", "rmdir")
  103. _add("HAVE_UTIMENSAT", "utime")
  104. supports_dir_fd = _set
  105. _set = set()
  106. _add("HAVE_FACCESSAT", "access")
  107. supports_effective_ids = _set
  108. _set = set()
  109. _add("HAVE_FCHDIR", "chdir")
  110. _add("HAVE_FCHMOD", "chmod")
  111. _add("HAVE_FCHOWN", "chown")
  112. _add("HAVE_FDOPENDIR", "listdir")
  113. _add("HAVE_FDOPENDIR", "scandir")
  114. _add("HAVE_FEXECVE", "execve")
  115. _set.add(stat) # fstat always works
  116. _add("HAVE_FTRUNCATE", "truncate")
  117. _add("HAVE_FUTIMENS", "utime")
  118. _add("HAVE_FUTIMES", "utime")
  119. _add("HAVE_FPATHCONF", "pathconf")
  120. if _exists("statvfs") and _exists("fstatvfs"): # mac os x10.3
  121. _add("HAVE_FSTATVFS", "statvfs")
  122. supports_fd = _set
  123. _set = set()
  124. _add("HAVE_FACCESSAT", "access")
  125. # Some platforms don't support lchmod(). Often the function exists
  126. # anyway, as a stub that always returns ENOSUP or perhaps EOPNOTSUPP.
  127. # (No, I don't know why that's a good design.) ./configure will detect
  128. # this and reject it--so HAVE_LCHMOD still won't be defined on such
  129. # platforms. This is Very Helpful.
  130. #
  131. # However, sometimes platforms without a working lchmod() *do* have
  132. # fchmodat(). (Examples: Linux kernel 3.2 with glibc 2.15,
  133. # OpenIndiana 3.x.) And fchmodat() has a flag that theoretically makes
  134. # it behave like lchmod(). So in theory it would be a suitable
  135. # replacement for lchmod(). But when lchmod() doesn't work, fchmodat()'s
  136. # flag doesn't work *either*. Sadly ./configure isn't sophisticated
  137. # enough to detect this condition--it only determines whether or not
  138. # fchmodat() minimally works.
  139. #
  140. # Therefore we simply ignore fchmodat() when deciding whether or not
  141. # os.chmod supports follow_symlinks. Just checking lchmod() is
  142. # sufficient. After all--if you have a working fchmodat(), your
  143. # lchmod() almost certainly works too.
  144. #
  145. # _add("HAVE_FCHMODAT", "chmod")
  146. _add("HAVE_FCHOWNAT", "chown")
  147. _add("HAVE_FSTATAT", "stat")
  148. _add("HAVE_LCHFLAGS", "chflags")
  149. _add("HAVE_LCHMOD", "chmod")
  150. if _exists("lchown"): # mac os x10.3
  151. _add("HAVE_LCHOWN", "chown")
  152. _add("HAVE_LINKAT", "link")
  153. _add("HAVE_LUTIMES", "utime")
  154. _add("HAVE_LSTAT", "stat")
  155. _add("HAVE_FSTATAT", "stat")
  156. _add("HAVE_UTIMENSAT", "utime")
  157. _add("MS_WINDOWS", "stat")
  158. supports_follow_symlinks = _set
  159. del _set
  160. del _have_functions
  161. del _globals
  162. del _add
  163. # Python uses fixed values for the SEEK_ constants; they are mapped
  164. # to native constants if necessary in posixmodule.c
  165. # Other possible SEEK values are directly imported from posixmodule.c
  166. SEEK_SET = 0
  167. SEEK_CUR = 1
  168. SEEK_END = 2
  169. # Super directory utilities.
  170. # (Inspired by Eric Raymond; the doc strings are mostly his)
  171. def makedirs(name, mode=0o777, exist_ok=False):
  172. """makedirs(name [, mode=0o777][, exist_ok=False])
  173. Super-mkdir; create a leaf directory and all intermediate ones. Works like
  174. mkdir, except that any intermediate path segment (not just the rightmost)
  175. will be created if it does not exist. If the target directory already
  176. exists, raise an OSError if exist_ok is False. Otherwise no exception is
  177. raised. This is recursive.
  178. """
  179. head, tail = path.split(name)
  180. if not tail:
  181. head, tail = path.split(head)
  182. if head and tail and not path.exists(head):
  183. try:
  184. makedirs(head, exist_ok=exist_ok)
  185. except FileExistsError:
  186. # Defeats race condition when another thread created the path
  187. pass
  188. cdir = curdir
  189. if isinstance(tail, bytes):
  190. cdir = bytes(curdir, 'ASCII')
  191. if tail == cdir: # xxx/newdir/. exists if xxx/newdir exists
  192. return
  193. try:
  194. mkdir(name, mode)
  195. except OSError:
  196. # Cannot rely on checking for EEXIST, since the operating system
  197. # could give priority to other errors like EACCES or EROFS
  198. if not exist_ok or not path.isdir(name):
  199. raise
  200. def removedirs(name):
  201. """removedirs(name)
  202. Super-rmdir; remove a leaf directory and all empty intermediate
  203. ones. Works like rmdir except that, if the leaf directory is
  204. successfully removed, directories corresponding to rightmost path
  205. segments will be pruned away until either the whole path is
  206. consumed or an error occurs. Errors during this latter phase are
  207. ignored -- they generally mean that a directory was not empty.
  208. """
  209. rmdir(name)
  210. head, tail = path.split(name)
  211. if not tail:
  212. head, tail = path.split(head)
  213. while head and tail:
  214. try:
  215. rmdir(head)
  216. except OSError:
  217. break
  218. head, tail = path.split(head)
  219. def renames(old, new):
  220. """renames(old, new)
  221. Super-rename; create directories as necessary and delete any left
  222. empty. Works like rename, except creation of any intermediate
  223. directories needed to make the new pathname good is attempted
  224. first. After the rename, directories corresponding to rightmost
  225. path segments of the old name will be pruned until either the
  226. whole path is consumed or a nonempty directory is found.
  227. Note: this function can fail with the new directory structure made
  228. if you lack permissions needed to unlink the leaf directory or
  229. file.
  230. """
  231. head, tail = path.split(new)
  232. if head and tail and not path.exists(head):
  233. makedirs(head)
  234. rename(old, new)
  235. head, tail = path.split(old)
  236. if head and tail:
  237. try:
  238. removedirs(head)
  239. except OSError:
  240. pass
  241. __all__.extend(["makedirs", "removedirs", "renames"])
  242. def walk(top, topdown=True, onerror=None, followlinks=False):
  243. """Directory tree generator.
  244. For each directory in the directory tree rooted at top (including top
  245. itself, but excluding '.' and '..'), yields a 3-tuple
  246. dirpath, dirnames, filenames
  247. dirpath is a string, the path to the directory. dirnames is a list of
  248. the names of the subdirectories in dirpath (excluding '.' and '..').
  249. filenames is a list of the names of the non-directory files in dirpath.
  250. Note that the names in the lists are just names, with no path components.
  251. To get a full path (which begins with top) to a file or directory in
  252. dirpath, do os.path.join(dirpath, name).
  253. If optional arg 'topdown' is true or not specified, the triple for a
  254. directory is generated before the triples for any of its subdirectories
  255. (directories are generated top down). If topdown is false, the triple
  256. for a directory is generated after the triples for all of its
  257. subdirectories (directories are generated bottom up).
  258. When topdown is true, the caller can modify the dirnames list in-place
  259. (e.g., via del or slice assignment), and walk will only recurse into the
  260. subdirectories whose names remain in dirnames; this can be used to prune the
  261. search, or to impose a specific order of visiting. Modifying dirnames when
  262. topdown is false has no effect on the behavior of os.walk(), since the
  263. directories in dirnames have already been generated by the time dirnames
  264. itself is generated. No matter the value of topdown, the list of
  265. subdirectories is retrieved before the tuples for the directory and its
  266. subdirectories are generated.
  267. By default errors from the os.scandir() call are ignored. If
  268. optional arg 'onerror' is specified, it should be a function; it
  269. will be called with one argument, an OSError instance. It can
  270. report the error to continue with the walk, or raise the exception
  271. to abort the walk. Note that the filename is available as the
  272. filename attribute of the exception object.
  273. By default, os.walk does not follow symbolic links to subdirectories on
  274. systems that support them. In order to get this functionality, set the
  275. optional argument 'followlinks' to true.
  276. Caution: if you pass a relative pathname for top, don't change the
  277. current working directory between resumptions of walk. walk never
  278. changes the current directory, and assumes that the client doesn't
  279. either.
  280. Example:
  281. import os
  282. from os.path import join, getsize
  283. for root, dirs, files in os.walk('python/Lib/email'):
  284. print(root, "consumes", end="")
  285. print(sum(getsize(join(root, name)) for name in files), end="")
  286. print("bytes in", len(files), "non-directory files")
  287. if 'CVS' in dirs:
  288. dirs.remove('CVS') # don't visit CVS directories
  289. """
  290. sys.audit("os.walk", top, topdown, onerror, followlinks)
  291. return _walk(fspath(top), topdown, onerror, followlinks)
  292. def _walk(top, topdown, onerror, followlinks):
  293. dirs = []
  294. nondirs = []
  295. walk_dirs = []
  296. # We may not have read permission for top, in which case we can't
  297. # get a list of the files the directory contains. os.walk
  298. # always suppressed the exception then, rather than blow up for a
  299. # minor reason when (say) a thousand readable directories are still
  300. # left to visit. That logic is copied here.
  301. try:
  302. # Note that scandir is global in this module due
  303. # to earlier import-*.
  304. scandir_it = scandir(top)
  305. except OSError as error:
  306. if onerror is not None:
  307. onerror(error)
  308. return
  309. with scandir_it:
  310. while True:
  311. try:
  312. try:
  313. entry = next(scandir_it)
  314. except StopIteration:
  315. break
  316. except OSError as error:
  317. if onerror is not None:
  318. onerror(error)
  319. return
  320. try:
  321. is_dir = entry.is_dir()
  322. except OSError:
  323. # If is_dir() raises an OSError, consider that the entry is not
  324. # a directory, same behaviour than os.path.isdir().
  325. is_dir = False
  326. if is_dir:
  327. dirs.append(entry.name)
  328. else:
  329. nondirs.append(entry.name)
  330. if not topdown and is_dir:
  331. # Bottom-up: recurse into sub-directory, but exclude symlinks to
  332. # directories if followlinks is False
  333. if followlinks:
  334. walk_into = True
  335. else:
  336. try:
  337. is_symlink = entry.is_symlink()
  338. except OSError:
  339. # If is_symlink() raises an OSError, consider that the
  340. # entry is not a symbolic link, same behaviour than
  341. # os.path.islink().
  342. is_symlink = False
  343. walk_into = not is_symlink
  344. if walk_into:
  345. walk_dirs.append(entry.path)
  346. # Yield before recursion if going top down
  347. if topdown:
  348. yield top, dirs, nondirs
  349. # Recurse into sub-directories
  350. islink, join = path.islink, path.join
  351. for dirname in dirs:
  352. new_path = join(top, dirname)
  353. # Issue #23605: os.path.islink() is used instead of caching
  354. # entry.is_symlink() result during the loop on os.scandir() because
  355. # the caller can replace the directory entry during the "yield"
  356. # above.
  357. if followlinks or not islink(new_path):
  358. yield from _walk(new_path, topdown, onerror, followlinks)
  359. else:
  360. # Recurse into sub-directories
  361. for new_path in walk_dirs:
  362. yield from _walk(new_path, topdown, onerror, followlinks)
  363. # Yield after recursion if going bottom up
  364. yield top, dirs, nondirs
  365. __all__.append("walk")
  366. if {open, stat} <= supports_dir_fd and {scandir, stat} <= supports_fd:
  367. def fwalk(top=".", topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None):
  368. """Directory tree generator.
  369. This behaves exactly like walk(), except that it yields a 4-tuple
  370. dirpath, dirnames, filenames, dirfd
  371. `dirpath`, `dirnames` and `filenames` are identical to walk() output,
  372. and `dirfd` is a file descriptor referring to the directory `dirpath`.
  373. The advantage of fwalk() over walk() is that it's safe against symlink
  374. races (when follow_symlinks is False).
  375. If dir_fd is not None, it should be a file descriptor open to a directory,
  376. and top should be relative; top will then be relative to that directory.
  377. (dir_fd is always supported for fwalk.)
  378. Caution:
  379. Since fwalk() yields file descriptors, those are only valid until the
  380. next iteration step, so you should dup() them if you want to keep them
  381. for a longer period.
  382. Example:
  383. import os
  384. for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
  385. print(root, "consumes", end="")
  386. print(sum(os.stat(name, dir_fd=rootfd).st_size for name in files),
  387. end="")
  388. print("bytes in", len(files), "non-directory files")
  389. if 'CVS' in dirs:
  390. dirs.remove('CVS') # don't visit CVS directories
  391. """
  392. sys.audit("os.fwalk", top, topdown, onerror, follow_symlinks, dir_fd)
  393. if not isinstance(top, int) or not hasattr(top, '__index__'):
  394. top = fspath(top)
  395. # Note: To guard against symlink races, we use the standard
  396. # lstat()/open()/fstat() trick.
  397. if not follow_symlinks:
  398. orig_st = stat(top, follow_symlinks=False, dir_fd=dir_fd)
  399. topfd = open(top, O_RDONLY, dir_fd=dir_fd)
  400. try:
  401. if (follow_symlinks or (st.S_ISDIR(orig_st.st_mode) and
  402. path.samestat(orig_st, stat(topfd)))):
  403. yield from _fwalk(topfd, top, isinstance(top, bytes),
  404. topdown, onerror, follow_symlinks)
  405. finally:
  406. close(topfd)
  407. def _fwalk(topfd, toppath, isbytes, topdown, onerror, follow_symlinks):
  408. # Note: This uses O(depth of the directory tree) file descriptors: if
  409. # necessary, it can be adapted to only require O(1) FDs, see issue
  410. # #13734.
  411. scandir_it = scandir(topfd)
  412. dirs = []
  413. nondirs = []
  414. entries = None if topdown or follow_symlinks else []
  415. for entry in scandir_it:
  416. name = entry.name
  417. if isbytes:
  418. name = fsencode(name)
  419. try:
  420. if entry.is_dir():
  421. dirs.append(name)
  422. if entries is not None:
  423. entries.append(entry)
  424. else:
  425. nondirs.append(name)
  426. except OSError:
  427. try:
  428. # Add dangling symlinks, ignore disappeared files
  429. if entry.is_symlink():
  430. nondirs.append(name)
  431. except OSError:
  432. pass
  433. if topdown:
  434. yield toppath, dirs, nondirs, topfd
  435. for name in dirs if entries is None else zip(dirs, entries):
  436. try:
  437. if not follow_symlinks:
  438. if topdown:
  439. orig_st = stat(name, dir_fd=topfd, follow_symlinks=False)
  440. else:
  441. assert entries is not None
  442. name, entry = name
  443. orig_st = entry.stat(follow_symlinks=False)
  444. dirfd = open(name, O_RDONLY, dir_fd=topfd)
  445. except OSError as err:
  446. if onerror is not None:
  447. onerror(err)
  448. continue
  449. try:
  450. if follow_symlinks or path.samestat(orig_st, stat(dirfd)):
  451. dirpath = path.join(toppath, name)
  452. yield from _fwalk(dirfd, dirpath, isbytes,
  453. topdown, onerror, follow_symlinks)
  454. finally:
  455. close(dirfd)
  456. if not topdown:
  457. yield toppath, dirs, nondirs, topfd
  458. __all__.append("fwalk")
  459. def execl(file, *args):
  460. """execl(file, *args)
  461. Execute the executable file with argument list args, replacing the
  462. current process. """
  463. execv(file, args)
  464. def execle(file, *args):
  465. """execle(file, *args, env)
  466. Execute the executable file with argument list args and
  467. environment env, replacing the current process. """
  468. env = args[-1]
  469. execve(file, args[:-1], env)
  470. def execlp(file, *args):
  471. """execlp(file, *args)
  472. Execute the executable file (which is searched for along $PATH)
  473. with argument list args, replacing the current process. """
  474. execvp(file, args)
  475. def execlpe(file, *args):
  476. """execlpe(file, *args, env)
  477. Execute the executable file (which is searched for along $PATH)
  478. with argument list args and environment env, replacing the current
  479. process. """
  480. env = args[-1]
  481. execvpe(file, args[:-1], env)
  482. def execvp(file, args):
  483. """execvp(file, args)
  484. Execute the executable file (which is searched for along $PATH)
  485. with argument list args, replacing the current process.
  486. args may be a list or tuple of strings. """
  487. _execvpe(file, args)
  488. def execvpe(file, args, env):
  489. """execvpe(file, args, env)
  490. Execute the executable file (which is searched for along $PATH)
  491. with argument list args and environment env, replacing the
  492. current process.
  493. args may be a list or tuple of strings. """
  494. _execvpe(file, args, env)
  495. __all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])
  496. def _execvpe(file, args, env=None):
  497. if env is not None:
  498. exec_func = execve
  499. argrest = (args, env)
  500. else:
  501. exec_func = execv
  502. argrest = (args,)
  503. env = environ
  504. if path.dirname(file):
  505. exec_func(file, *argrest)
  506. return
  507. saved_exc = None
  508. path_list = get_exec_path(env)
  509. if name != 'nt':
  510. file = fsencode(file)
  511. path_list = map(fsencode, path_list)
  512. for dir in path_list:
  513. fullname = path.join(dir, file)
  514. try:
  515. exec_func(fullname, *argrest)
  516. except (FileNotFoundError, NotADirectoryError) as e:
  517. last_exc = e
  518. except OSError as e:
  519. last_exc = e
  520. if saved_exc is None:
  521. saved_exc = e
  522. if saved_exc is not None:
  523. raise saved_exc
  524. raise last_exc
  525. def get_exec_path(env=None):
  526. """Returns the sequence of directories that will be searched for the
  527. named executable (similar to a shell) when launching a process.
  528. *env* must be an environment variable dict or None. If *env* is None,
  529. os.environ will be used.
  530. """
  531. # Use a local import instead of a global import to limit the number of
  532. # modules loaded at startup: the os module is always loaded at startup by
  533. # Python. It may also avoid a bootstrap issue.
  534. import warnings
  535. if env is None:
  536. env = environ
  537. # {b'PATH': ...}.get('PATH') and {'PATH': ...}.get(b'PATH') emit a
  538. # BytesWarning when using python -b or python -bb: ignore the warning
  539. with warnings.catch_warnings():
  540. warnings.simplefilter("ignore", BytesWarning)
  541. try:
  542. path_list = env.get('PATH')
  543. except TypeError:
  544. path_list = None
  545. if supports_bytes_environ:
  546. try:
  547. path_listb = env[b'PATH']
  548. except (KeyError, TypeError):
  549. pass
  550. else:
  551. if path_list is not None:
  552. raise ValueError(
  553. "env cannot contain 'PATH' and b'PATH' keys")
  554. path_list = path_listb
  555. if path_list is not None and isinstance(path_list, bytes):
  556. path_list = fsdecode(path_list)
  557. if path_list is None:
  558. path_list = defpath
  559. return path_list.split(pathsep)
  560. # Change environ to automatically call putenv() and unsetenv()
  561. from _collections_abc import MutableMapping, Mapping
  562. class _Environ(MutableMapping):
  563. def __init__(self, data, encodekey, decodekey, encodevalue, decodevalue):
  564. self.encodekey = encodekey
  565. self.decodekey = decodekey
  566. self.encodevalue = encodevalue
  567. self.decodevalue = decodevalue
  568. self._data = data
  569. def __getitem__(self, key):
  570. try:
  571. value = self._data[self.encodekey(key)]
  572. except KeyError:
  573. # raise KeyError with the original key value
  574. raise KeyError(key) from None
  575. return self.decodevalue(value)
  576. def __setitem__(self, key, value):
  577. key = self.encodekey(key)
  578. value = self.encodevalue(value)
  579. putenv(key, value)
  580. self._data[key] = value
  581. def __delitem__(self, key):
  582. encodedkey = self.encodekey(key)
  583. unsetenv(encodedkey)
  584. try:
  585. del self._data[encodedkey]
  586. except KeyError:
  587. # raise KeyError with the original key value
  588. raise KeyError(key) from None
  589. def __iter__(self):
  590. # list() from dict object is an atomic operation
  591. keys = list(self._data)
  592. for key in keys:
  593. yield self.decodekey(key)
  594. def __len__(self):
  595. return len(self._data)
  596. def __repr__(self):
  597. return 'environ({{{}}})'.format(', '.join(
  598. ('{!r}: {!r}'.format(self.decodekey(key), self.decodevalue(value))
  599. for key, value in self._data.items())))
  600. def copy(self):
  601. return dict(self)
  602. def setdefault(self, key, value):
  603. if key not in self:
  604. self[key] = value
  605. return self[key]
  606. def __ior__(self, other):
  607. self.update(other)
  608. return self
  609. def __or__(self, other):
  610. if not isinstance(other, Mapping):
  611. return NotImplemented
  612. new = dict(self)
  613. new.update(other)
  614. return new
  615. def __ror__(self, other):
  616. if not isinstance(other, Mapping):
  617. return NotImplemented
  618. new = dict(other)
  619. new.update(self)
  620. return new
  621. def _createenviron():
  622. if name == 'nt':
  623. # Where Env Var Names Must Be UPPERCASE
  624. def check_str(value):
  625. if not isinstance(value, str):
  626. raise TypeError("str expected, not %s" % type(value).__name__)
  627. return value
  628. encode = check_str
  629. decode = str
  630. def encodekey(key):
  631. return encode(key).upper()
  632. data = {}
  633. for key, value in environ.items():
  634. data[encodekey(key)] = value
  635. else:
  636. # Where Env Var Names Can Be Mixed Case
  637. encoding = sys.getfilesystemencoding()
  638. def encode(value):
  639. if not isinstance(value, str):
  640. raise TypeError("str expected, not %s" % type(value).__name__)
  641. return value.encode(encoding, 'surrogateescape')
  642. def decode(value):
  643. return value.decode(encoding, 'surrogateescape')
  644. encodekey = encode
  645. data = environ
  646. return _Environ(data,
  647. encodekey, decode,
  648. encode, decode)
  649. # unicode environ
  650. environ = _createenviron()
  651. del _createenviron
  652. def getenv(key, default=None):
  653. """Get an environment variable, return None if it doesn't exist.
  654. The optional second argument can specify an alternate default.
  655. key, default and the result are str."""
  656. return environ.get(key, default)
  657. supports_bytes_environ = (name != 'nt')
  658. __all__.extend(("getenv", "supports_bytes_environ"))
  659. if supports_bytes_environ:
  660. def _check_bytes(value):
  661. if not isinstance(value, bytes):
  662. raise TypeError("bytes expected, not %s" % type(value).__name__)
  663. return value
  664. # bytes environ
  665. environb = _Environ(environ._data,
  666. _check_bytes, bytes,
  667. _check_bytes, bytes)
  668. del _check_bytes
  669. def getenvb(key, default=None):
  670. """Get an environment variable, return None if it doesn't exist.
  671. The optional second argument can specify an alternate default.
  672. key, default and the result are bytes."""
  673. return environb.get(key, default)
  674. __all__.extend(("environb", "getenvb"))
  675. def _fscodec():
  676. encoding = sys.getfilesystemencoding()
  677. errors = sys.getfilesystemencodeerrors()
  678. def fsencode(filename):
  679. """Encode filename (an os.PathLike, bytes, or str) to the filesystem
  680. encoding with 'surrogateescape' error handler, return bytes unchanged.
  681. On Windows, use 'strict' error handler if the file system encoding is
  682. 'mbcs' (which is the default encoding).
  683. """
  684. filename = fspath(filename) # Does type-checking of `filename`.
  685. if isinstance(filename, str):
  686. return filename.encode(encoding, errors)
  687. else:
  688. return filename
  689. def fsdecode(filename):
  690. """Decode filename (an os.PathLike, bytes, or str) from the filesystem
  691. encoding with 'surrogateescape' error handler, return str unchanged. On
  692. Windows, use 'strict' error handler if the file system encoding is
  693. 'mbcs' (which is the default encoding).
  694. """
  695. filename = fspath(filename) # Does type-checking of `filename`.
  696. if isinstance(filename, bytes):
  697. return filename.decode(encoding, errors)
  698. else:
  699. return filename
  700. return fsencode, fsdecode
  701. fsencode, fsdecode = _fscodec()
  702. del _fscodec
  703. # Supply spawn*() (probably only for Unix)
  704. if _exists("fork") and not _exists("spawnv") and _exists("execv"):
  705. P_WAIT = 0
  706. P_NOWAIT = P_NOWAITO = 1
  707. __all__.extend(["P_WAIT", "P_NOWAIT", "P_NOWAITO"])
  708. # XXX Should we support P_DETACH? I suppose it could fork()**2
  709. # and close the std I/O streams. Also, P_OVERLAY is the same
  710. # as execv*()?
  711. def _spawnvef(mode, file, args, env, func):
  712. # Internal helper; func is the exec*() function to use
  713. if not isinstance(args, (tuple, list)):
  714. raise TypeError('argv must be a tuple or a list')
  715. if not args or not args[0]:
  716. raise ValueError('argv first element cannot be empty')
  717. pid = fork()
  718. if not pid:
  719. # Child
  720. try:
  721. if env is None:
  722. func(file, args)
  723. else:
  724. func(file, args, env)
  725. except:
  726. _exit(127)
  727. else:
  728. # Parent
  729. if mode == P_NOWAIT:
  730. return pid # Caller is responsible for waiting!
  731. while 1:
  732. wpid, sts = waitpid(pid, 0)
  733. if WIFSTOPPED(sts):
  734. continue
  735. return waitstatus_to_exitcode(sts)
  736. def spawnv(mode, file, args):
  737. """spawnv(mode, file, args) -> integer
  738. Execute file with arguments from args in a subprocess.
  739. If mode == P_NOWAIT return the pid of the process.
  740. If mode == P_WAIT return the process's exit code if it exits normally;
  741. otherwise return -SIG, where SIG is the signal that killed it. """
  742. return _spawnvef(mode, file, args, None, execv)
  743. def spawnve(mode, file, args, env):
  744. """spawnve(mode, file, args, env) -> integer
  745. Execute file with arguments from args in a subprocess with the
  746. specified environment.
  747. If mode == P_NOWAIT return the pid of the process.
  748. If mode == P_WAIT return the process's exit code if it exits normally;
  749. otherwise return -SIG, where SIG is the signal that killed it. """
  750. return _spawnvef(mode, file, args, env, execve)
  751. # Note: spawnvp[e] isn't currently supported on Windows
  752. def spawnvp(mode, file, args):
  753. """spawnvp(mode, file, args) -> integer
  754. Execute file (which is looked for along $PATH) with arguments from
  755. args in a subprocess.
  756. If mode == P_NOWAIT return the pid of the process.
  757. If mode == P_WAIT return the process's exit code if it exits normally;
  758. otherwise return -SIG, where SIG is the signal that killed it. """
  759. return _spawnvef(mode, file, args, None, execvp)
  760. def spawnvpe(mode, file, args, env):
  761. """spawnvpe(mode, file, args, env) -> integer
  762. Execute file (which is looked for along $PATH) with arguments from
  763. args in a subprocess with the supplied environment.
  764. If mode == P_NOWAIT return the pid of the process.
  765. If mode == P_WAIT return the process's exit code if it exits normally;
  766. otherwise return -SIG, where SIG is the signal that killed it. """
  767. return _spawnvef(mode, file, args, env, execvpe)
  768. __all__.extend(["spawnv", "spawnve", "spawnvp", "spawnvpe"])
  769. if _exists("spawnv"):
  770. # These aren't supplied by the basic Windows code
  771. # but can be easily implemented in Python
  772. def spawnl(mode, file, *args):
  773. """spawnl(mode, file, *args) -> integer
  774. Execute file with arguments from args in a subprocess.
  775. If mode == P_NOWAIT return the pid of the process.
  776. If mode == P_WAIT return the process's exit code if it exits normally;
  777. otherwise return -SIG, where SIG is the signal that killed it. """
  778. return spawnv(mode, file, args)
  779. def spawnle(mode, file, *args):
  780. """spawnle(mode, file, *args, env) -> integer
  781. Execute file with arguments from args in a subprocess with the
  782. supplied environment.
  783. If mode == P_NOWAIT return the pid of the process.
  784. If mode == P_WAIT return the process's exit code if it exits normally;
  785. otherwise return -SIG, where SIG is the signal that killed it. """
  786. env = args[-1]
  787. return spawnve(mode, file, args[:-1], env)
  788. __all__.extend(["spawnl", "spawnle"])
  789. if _exists("spawnvp"):
  790. # At the moment, Windows doesn't implement spawnvp[e],
  791. # so it won't have spawnlp[e] either.
  792. def spawnlp(mode, file, *args):
  793. """spawnlp(mode, file, *args) -> integer
  794. Execute file (which is looked for along $PATH) with arguments from
  795. args in a subprocess with the supplied environment.
  796. If mode == P_NOWAIT return the pid of the process.
  797. If mode == P_WAIT return the process's exit code if it exits normally;
  798. otherwise return -SIG, where SIG is the signal that killed it. """
  799. return spawnvp(mode, file, args)
  800. def spawnlpe(mode, file, *args):
  801. """spawnlpe(mode, file, *args, env) -> integer
  802. Execute file (which is looked for along $PATH) with arguments from
  803. args in a subprocess with the supplied environment.
  804. If mode == P_NOWAIT return the pid of the process.
  805. If mode == P_WAIT return the process's exit code if it exits normally;
  806. otherwise return -SIG, where SIG is the signal that killed it. """
  807. env = args[-1]
  808. return spawnvpe(mode, file, args[:-1], env)
  809. __all__.extend(["spawnlp", "spawnlpe"])
  810. # Supply os.popen()
  811. def popen(cmd, mode="r", buffering=-1):
  812. if not isinstance(cmd, str):
  813. raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
  814. if mode not in ("r", "w"):
  815. raise ValueError("invalid mode %r" % mode)
  816. if buffering == 0 or buffering is None:
  817. raise ValueError("popen() does not support unbuffered streams")
  818. import subprocess, io
  819. if mode == "r":
  820. proc = subprocess.Popen(cmd,
  821. shell=True,
  822. stdout=subprocess.PIPE,
  823. bufsize=buffering)
  824. return _wrap_close(io.TextIOWrapper(proc.stdout), proc)
  825. else:
  826. proc = subprocess.Popen(cmd,
  827. shell=True,
  828. stdin=subprocess.PIPE,
  829. bufsize=buffering)
  830. return _wrap_close(io.TextIOWrapper(proc.stdin), proc)
  831. # Helper for popen() -- a proxy for a file whose close waits for the process
  832. class _wrap_close:
  833. def __init__(self, stream, proc):
  834. self._stream = stream
  835. self._proc = proc
  836. def close(self):
  837. self._stream.close()
  838. returncode = self._proc.wait()
  839. if returncode == 0:
  840. return None
  841. if name == 'nt':
  842. return returncode
  843. else:
  844. return returncode << 8 # Shift left to match old behavior
  845. def __enter__(self):
  846. return self
  847. def __exit__(self, *args):
  848. self.close()
  849. def __getattr__(self, name):
  850. return getattr(self._stream, name)
  851. def __iter__(self):
  852. return iter(self._stream)
  853. # Supply os.fdopen()
  854. def fdopen(fd, *args, **kwargs):
  855. if not isinstance(fd, int):
  856. raise TypeError("invalid fd type (%s, expected integer)" % type(fd))
  857. import io
  858. return io.open(fd, *args, **kwargs)
  859. # For testing purposes, make sure the function is available when the C
  860. # implementation exists.
  861. def _fspath(path):
  862. """Return the path representation of a path-like object.
  863. If str or bytes is passed in, it is returned unchanged. Otherwise the
  864. os.PathLike interface is used to get the path representation. If the
  865. path representation is not str or bytes, TypeError is raised. If the
  866. provided path is not str, bytes, or os.PathLike, TypeError is raised.
  867. """
  868. if isinstance(path, (str, bytes)):
  869. return path
  870. # Work from the object's type to match method resolution of other magic
  871. # methods.
  872. path_type = type(path)
  873. try:
  874. path_repr = path_type.__fspath__(path)
  875. except AttributeError:
  876. if hasattr(path_type, '__fspath__'):
  877. raise
  878. else:
  879. raise TypeError("expected str, bytes or os.PathLike object, "
  880. "not " + path_type.__name__)
  881. if isinstance(path_repr, (str, bytes)):
  882. return path_repr
  883. else:
  884. raise TypeError("expected {}.__fspath__() to return str or bytes, "
  885. "not {}".format(path_type.__name__,
  886. type(path_repr).__name__))
  887. # If there is no C implementation, make the pure Python version the
  888. # implementation as transparently as possible.
  889. if not _exists('fspath'):
  890. fspath = _fspath
  891. fspath.__name__ = "fspath"
  892. class PathLike(abc.ABC):
  893. """Abstract base class for implementing the file system path protocol."""
  894. @abc.abstractmethod
  895. def __fspath__(self):
  896. """Return the file system path representation of the object."""
  897. raise NotImplementedError
  898. @classmethod
  899. def __subclasshook__(cls, subclass):
  900. if cls is PathLike:
  901. return _check_methods(subclass, '__fspath__')
  902. return NotImplemented
  903. __class_getitem__ = classmethod(GenericAlias)
  904. if name == 'nt':
  905. class _AddedDllDirectory:
  906. def __init__(self, path, cookie, remove_dll_directory):
  907. self.path = path
  908. self._cookie = cookie
  909. self._remove_dll_directory = remove_dll_directory
  910. def close(self):
  911. self._remove_dll_directory(self._cookie)
  912. self.path = None
  913. def __enter__(self):
  914. return self
  915. def __exit__(self, *args):
  916. self.close()
  917. def __repr__(self):
  918. if self.path:
  919. return "<AddedDllDirectory({!r})>".format(self.path)
  920. return "<AddedDllDirectory()>"
  921. def add_dll_directory(path):
  922. """Add a path to the DLL search path.
  923. This search path is used when resolving dependencies for imported
  924. extension modules (the module itself is resolved through sys.path),
  925. and also by ctypes.
  926. Remove the directory by calling close() on the returned object or
  927. using it in a with statement.
  928. """
  929. import nt
  930. cookie = nt._add_dll_directory(path)
  931. return _AddedDllDirectory(
  932. path,
  933. cookie,
  934. nt._remove_dll_directory
  935. )