os.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  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. "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. # Private sentinel that makes walk() classify all symlinks and junctions as
  243. # regular files.
  244. _walk_symlinks_as_files = object()
  245. def walk(top, topdown=True, onerror=None, followlinks=False):
  246. """Directory tree generator.
  247. For each directory in the directory tree rooted at top (including top
  248. itself, but excluding '.' and '..'), yields a 3-tuple
  249. dirpath, dirnames, filenames
  250. dirpath is a string, the path to the directory. dirnames is a list of
  251. the names of the subdirectories in dirpath (including symlinks to directories,
  252. and excluding '.' and '..').
  253. filenames is a list of the names of the non-directory files in dirpath.
  254. Note that the names in the lists are just names, with no path components.
  255. To get a full path (which begins with top) to a file or directory in
  256. dirpath, do os.path.join(dirpath, name).
  257. If optional arg 'topdown' is true or not specified, the triple for a
  258. directory is generated before the triples for any of its subdirectories
  259. (directories are generated top down). If topdown is false, the triple
  260. for a directory is generated after the triples for all of its
  261. subdirectories (directories are generated bottom up).
  262. When topdown is true, the caller can modify the dirnames list in-place
  263. (e.g., via del or slice assignment), and walk will only recurse into the
  264. subdirectories whose names remain in dirnames; this can be used to prune the
  265. search, or to impose a specific order of visiting. Modifying dirnames when
  266. topdown is false has no effect on the behavior of os.walk(), since the
  267. directories in dirnames have already been generated by the time dirnames
  268. itself is generated. No matter the value of topdown, the list of
  269. subdirectories is retrieved before the tuples for the directory and its
  270. subdirectories are generated.
  271. By default errors from the os.scandir() call are ignored. If
  272. optional arg 'onerror' is specified, it should be a function; it
  273. will be called with one argument, an OSError instance. It can
  274. report the error to continue with the walk, or raise the exception
  275. to abort the walk. Note that the filename is available as the
  276. filename attribute of the exception object.
  277. By default, os.walk does not follow symbolic links to subdirectories on
  278. systems that support them. In order to get this functionality, set the
  279. optional argument 'followlinks' to true.
  280. Caution: if you pass a relative pathname for top, don't change the
  281. current working directory between resumptions of walk. walk never
  282. changes the current directory, and assumes that the client doesn't
  283. either.
  284. Example:
  285. import os
  286. from os.path import join, getsize
  287. for root, dirs, files in os.walk('python/Lib/email'):
  288. print(root, "consumes ")
  289. print(sum(getsize(join(root, name)) for name in files), end=" ")
  290. print("bytes in", len(files), "non-directory files")
  291. if 'CVS' in dirs:
  292. dirs.remove('CVS') # don't visit CVS directories
  293. """
  294. sys.audit("os.walk", top, topdown, onerror, followlinks)
  295. stack = [fspath(top)]
  296. islink, join = path.islink, path.join
  297. while stack:
  298. top = stack.pop()
  299. if isinstance(top, tuple):
  300. yield top
  301. continue
  302. dirs = []
  303. nondirs = []
  304. walk_dirs = []
  305. # We may not have read permission for top, in which case we can't
  306. # get a list of the files the directory contains.
  307. # We suppress the exception here, rather than blow up for a
  308. # minor reason when (say) a thousand readable directories are still
  309. # left to visit.
  310. try:
  311. scandir_it = scandir(top)
  312. except OSError as error:
  313. if onerror is not None:
  314. onerror(error)
  315. continue
  316. cont = False
  317. with scandir_it:
  318. while True:
  319. try:
  320. try:
  321. entry = next(scandir_it)
  322. except StopIteration:
  323. break
  324. except OSError as error:
  325. if onerror is not None:
  326. onerror(error)
  327. cont = True
  328. break
  329. try:
  330. if followlinks is _walk_symlinks_as_files:
  331. is_dir = entry.is_dir(follow_symlinks=False) and not entry.is_junction()
  332. else:
  333. is_dir = entry.is_dir()
  334. except OSError:
  335. # If is_dir() raises an OSError, consider the entry not to
  336. # be a directory, same behaviour as os.path.isdir().
  337. is_dir = False
  338. if is_dir:
  339. dirs.append(entry.name)
  340. else:
  341. nondirs.append(entry.name)
  342. if not topdown and is_dir:
  343. # Bottom-up: traverse into sub-directory, but exclude
  344. # symlinks to directories if followlinks is False
  345. if followlinks:
  346. walk_into = True
  347. else:
  348. try:
  349. is_symlink = entry.is_symlink()
  350. except OSError:
  351. # If is_symlink() raises an OSError, consider the
  352. # entry not to be a symbolic link, same behaviour
  353. # as os.path.islink().
  354. is_symlink = False
  355. walk_into = not is_symlink
  356. if walk_into:
  357. walk_dirs.append(entry.path)
  358. if cont:
  359. continue
  360. if topdown:
  361. # Yield before sub-directory traversal if going top down
  362. yield top, dirs, nondirs
  363. # Traverse into sub-directories
  364. for dirname in reversed(dirs):
  365. new_path = join(top, dirname)
  366. # bpo-23605: os.path.islink() is used instead of caching
  367. # entry.is_symlink() result during the loop on os.scandir() because
  368. # the caller can replace the directory entry during the "yield"
  369. # above.
  370. if followlinks or not islink(new_path):
  371. stack.append(new_path)
  372. else:
  373. # Yield after sub-directory traversal if going bottom up
  374. stack.append((top, dirs, nondirs))
  375. # Traverse into sub-directories
  376. for new_path in reversed(walk_dirs):
  377. stack.append(new_path)
  378. __all__.append("walk")
  379. if {open, stat} <= supports_dir_fd and {scandir, stat} <= supports_fd:
  380. def fwalk(top=".", topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None):
  381. """Directory tree generator.
  382. This behaves exactly like walk(), except that it yields a 4-tuple
  383. dirpath, dirnames, filenames, dirfd
  384. `dirpath`, `dirnames` and `filenames` are identical to walk() output,
  385. and `dirfd` is a file descriptor referring to the directory `dirpath`.
  386. The advantage of fwalk() over walk() is that it's safe against symlink
  387. races (when follow_symlinks is False).
  388. If dir_fd is not None, it should be a file descriptor open to a directory,
  389. and top should be relative; top will then be relative to that directory.
  390. (dir_fd is always supported for fwalk.)
  391. Caution:
  392. Since fwalk() yields file descriptors, those are only valid until the
  393. next iteration step, so you should dup() them if you want to keep them
  394. for a longer period.
  395. Example:
  396. import os
  397. for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
  398. print(root, "consumes", end="")
  399. print(sum(os.stat(name, dir_fd=rootfd).st_size for name in files),
  400. end="")
  401. print("bytes in", len(files), "non-directory files")
  402. if 'CVS' in dirs:
  403. dirs.remove('CVS') # don't visit CVS directories
  404. """
  405. sys.audit("os.fwalk", top, topdown, onerror, follow_symlinks, dir_fd)
  406. top = fspath(top)
  407. stack = [(_fwalk_walk, (True, dir_fd, top, top, None))]
  408. isbytes = isinstance(top, bytes)
  409. try:
  410. while stack:
  411. yield from _fwalk(stack, isbytes, topdown, onerror, follow_symlinks)
  412. finally:
  413. # Close any file descriptors still on the stack.
  414. while stack:
  415. action, value = stack.pop()
  416. if action == _fwalk_close:
  417. close(value)
  418. # Each item in the _fwalk() stack is a pair (action, args).
  419. _fwalk_walk = 0 # args: (isroot, dirfd, toppath, topname, entry)
  420. _fwalk_yield = 1 # args: (toppath, dirnames, filenames, topfd)
  421. _fwalk_close = 2 # args: dirfd
  422. def _fwalk(stack, isbytes, topdown, onerror, follow_symlinks):
  423. # Note: This uses O(depth of the directory tree) file descriptors: if
  424. # necessary, it can be adapted to only require O(1) FDs, see issue
  425. # #13734.
  426. action, value = stack.pop()
  427. if action == _fwalk_close:
  428. close(value)
  429. return
  430. elif action == _fwalk_yield:
  431. yield value
  432. return
  433. assert action == _fwalk_walk
  434. isroot, dirfd, toppath, topname, entry = value
  435. try:
  436. if not follow_symlinks:
  437. # Note: To guard against symlink races, we use the standard
  438. # lstat()/open()/fstat() trick.
  439. if entry is None:
  440. orig_st = stat(topname, follow_symlinks=False, dir_fd=dirfd)
  441. else:
  442. orig_st = entry.stat(follow_symlinks=False)
  443. topfd = open(topname, O_RDONLY | O_NONBLOCK, dir_fd=dirfd)
  444. except OSError as err:
  445. if isroot:
  446. raise
  447. if onerror is not None:
  448. onerror(err)
  449. return
  450. stack.append((_fwalk_close, topfd))
  451. if not follow_symlinks:
  452. if isroot and not st.S_ISDIR(orig_st.st_mode):
  453. return
  454. if not path.samestat(orig_st, stat(topfd)):
  455. return
  456. scandir_it = scandir(topfd)
  457. dirs = []
  458. nondirs = []
  459. entries = None if topdown or follow_symlinks else []
  460. for entry in scandir_it:
  461. name = entry.name
  462. if isbytes:
  463. name = fsencode(name)
  464. try:
  465. if entry.is_dir():
  466. dirs.append(name)
  467. if entries is not None:
  468. entries.append(entry)
  469. else:
  470. nondirs.append(name)
  471. except OSError:
  472. try:
  473. # Add dangling symlinks, ignore disappeared files
  474. if entry.is_symlink():
  475. nondirs.append(name)
  476. except OSError:
  477. pass
  478. if topdown:
  479. yield toppath, dirs, nondirs, topfd
  480. else:
  481. stack.append((_fwalk_yield, (toppath, dirs, nondirs, topfd)))
  482. toppath = path.join(toppath, toppath[:0]) # Add trailing slash.
  483. if entries is None:
  484. stack.extend(
  485. (_fwalk_walk, (False, topfd, toppath + name, name, None))
  486. for name in dirs[::-1])
  487. else:
  488. stack.extend(
  489. (_fwalk_walk, (False, topfd, toppath + name, name, entry))
  490. for name, entry in zip(dirs[::-1], entries[::-1]))
  491. __all__.append("fwalk")
  492. def execl(file, *args):
  493. """execl(file, *args)
  494. Execute the executable file with argument list args, replacing the
  495. current process. """
  496. execv(file, args)
  497. def execle(file, *args):
  498. """execle(file, *args, env)
  499. Execute the executable file with argument list args and
  500. environment env, replacing the current process. """
  501. env = args[-1]
  502. execve(file, args[:-1], env)
  503. def execlp(file, *args):
  504. """execlp(file, *args)
  505. Execute the executable file (which is searched for along $PATH)
  506. with argument list args, replacing the current process. """
  507. execvp(file, args)
  508. def execlpe(file, *args):
  509. """execlpe(file, *args, env)
  510. Execute the executable file (which is searched for along $PATH)
  511. with argument list args and environment env, replacing the current
  512. process. """
  513. env = args[-1]
  514. execvpe(file, args[:-1], env)
  515. def execvp(file, args):
  516. """execvp(file, args)
  517. Execute the executable file (which is searched for along $PATH)
  518. with argument list args, replacing the current process.
  519. args may be a list or tuple of strings. """
  520. _execvpe(file, args)
  521. def execvpe(file, args, env):
  522. """execvpe(file, args, env)
  523. Execute the executable file (which is searched for along $PATH)
  524. with argument list args and environment env, replacing the
  525. current process.
  526. args may be a list or tuple of strings. """
  527. _execvpe(file, args, env)
  528. __all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])
  529. def _execvpe(file, args, env=None):
  530. if env is not None:
  531. exec_func = execve
  532. argrest = (args, env)
  533. else:
  534. exec_func = execv
  535. argrest = (args,)
  536. env = environ
  537. if path.dirname(file):
  538. exec_func(file, *argrest)
  539. return
  540. saved_exc = None
  541. path_list = get_exec_path(env)
  542. if name != 'nt':
  543. file = fsencode(file)
  544. path_list = map(fsencode, path_list)
  545. for dir in path_list:
  546. fullname = path.join(dir, file)
  547. try:
  548. exec_func(fullname, *argrest)
  549. except (FileNotFoundError, NotADirectoryError) as e:
  550. last_exc = e
  551. except OSError as e:
  552. last_exc = e
  553. if saved_exc is None:
  554. saved_exc = e
  555. if saved_exc is not None:
  556. raise saved_exc
  557. raise last_exc
  558. def get_exec_path(env=None):
  559. """Returns the sequence of directories that will be searched for the
  560. named executable (similar to a shell) when launching a process.
  561. *env* must be an environment variable dict or None. If *env* is None,
  562. os.environ will be used.
  563. """
  564. # Use a local import instead of a global import to limit the number of
  565. # modules loaded at startup: the os module is always loaded at startup by
  566. # Python. It may also avoid a bootstrap issue.
  567. import warnings
  568. if env is None:
  569. env = environ
  570. # {b'PATH': ...}.get('PATH') and {'PATH': ...}.get(b'PATH') emit a
  571. # BytesWarning when using python -b or python -bb: ignore the warning
  572. with warnings.catch_warnings():
  573. warnings.simplefilter("ignore", BytesWarning)
  574. try:
  575. path_list = env.get('PATH')
  576. except TypeError:
  577. path_list = None
  578. if supports_bytes_environ:
  579. try:
  580. path_listb = env[b'PATH']
  581. except (KeyError, TypeError):
  582. pass
  583. else:
  584. if path_list is not None:
  585. raise ValueError(
  586. "env cannot contain 'PATH' and b'PATH' keys")
  587. path_list = path_listb
  588. if path_list is not None and isinstance(path_list, bytes):
  589. path_list = fsdecode(path_list)
  590. if path_list is None:
  591. path_list = defpath
  592. return path_list.split(pathsep)
  593. # Change environ to automatically call putenv() and unsetenv()
  594. from _collections_abc import MutableMapping, Mapping
  595. class _Environ(MutableMapping):
  596. def __init__(self, data, encodekey, decodekey, encodevalue, decodevalue):
  597. self.encodekey = encodekey
  598. self.decodekey = decodekey
  599. self.encodevalue = encodevalue
  600. self.decodevalue = decodevalue
  601. self._data = data
  602. def __getitem__(self, key):
  603. try:
  604. value = self._data[self.encodekey(key)]
  605. except KeyError:
  606. # raise KeyError with the original key value
  607. raise KeyError(key) from None
  608. return self.decodevalue(value)
  609. def __setitem__(self, key, value):
  610. key = self.encodekey(key)
  611. value = self.encodevalue(value)
  612. putenv(key, value)
  613. self._data[key] = value
  614. def __delitem__(self, key):
  615. encodedkey = self.encodekey(key)
  616. unsetenv(encodedkey)
  617. try:
  618. del self._data[encodedkey]
  619. except KeyError:
  620. # raise KeyError with the original key value
  621. raise KeyError(key) from None
  622. def __iter__(self):
  623. # list() from dict object is an atomic operation
  624. keys = list(self._data)
  625. for key in keys:
  626. yield self.decodekey(key)
  627. def __len__(self):
  628. return len(self._data)
  629. def __repr__(self):
  630. formatted_items = ", ".join(
  631. f"{self.decodekey(key)!r}: {self.decodevalue(value)!r}"
  632. for key, value in self._data.items()
  633. )
  634. return f"environ({{{formatted_items}}})"
  635. def copy(self):
  636. return dict(self)
  637. def setdefault(self, key, value):
  638. if key not in self:
  639. self[key] = value
  640. return self[key]
  641. def __ior__(self, other):
  642. self.update(other)
  643. return self
  644. def __or__(self, other):
  645. if not isinstance(other, Mapping):
  646. return NotImplemented
  647. new = dict(self)
  648. new.update(other)
  649. return new
  650. def __ror__(self, other):
  651. if not isinstance(other, Mapping):
  652. return NotImplemented
  653. new = dict(other)
  654. new.update(self)
  655. return new
  656. def _createenviron():
  657. if name == 'nt':
  658. # Where Env Var Names Must Be UPPERCASE
  659. def check_str(value):
  660. if not isinstance(value, str):
  661. raise TypeError("str expected, not %s" % type(value).__name__)
  662. return value
  663. encode = check_str
  664. decode = str
  665. def encodekey(key):
  666. return encode(key).upper()
  667. data = {}
  668. for key, value in environ.items():
  669. data[encodekey(key)] = value
  670. else:
  671. # Where Env Var Names Can Be Mixed Case
  672. encoding = sys.getfilesystemencoding()
  673. def encode(value):
  674. if not isinstance(value, str):
  675. raise TypeError("str expected, not %s" % type(value).__name__)
  676. return value.encode(encoding, 'surrogateescape')
  677. def decode(value):
  678. return value.decode(encoding, 'surrogateescape')
  679. encodekey = encode
  680. data = environ
  681. return _Environ(data,
  682. encodekey, decode,
  683. encode, decode)
  684. # unicode environ
  685. environ = _createenviron()
  686. del _createenviron
  687. def getenv(key, default=None):
  688. """Get an environment variable, return None if it doesn't exist.
  689. The optional second argument can specify an alternate default.
  690. key, default and the result are str."""
  691. return environ.get(key, default)
  692. supports_bytes_environ = (name != 'nt')
  693. __all__.extend(("getenv", "supports_bytes_environ"))
  694. if supports_bytes_environ:
  695. def _check_bytes(value):
  696. if not isinstance(value, bytes):
  697. raise TypeError("bytes expected, not %s" % type(value).__name__)
  698. return value
  699. # bytes environ
  700. environb = _Environ(environ._data,
  701. _check_bytes, bytes,
  702. _check_bytes, bytes)
  703. del _check_bytes
  704. def getenvb(key, default=None):
  705. """Get an environment variable, return None if it doesn't exist.
  706. The optional second argument can specify an alternate default.
  707. key, default and the result are bytes."""
  708. return environb.get(key, default)
  709. __all__.extend(("environb", "getenvb"))
  710. def _fscodec():
  711. encoding = sys.getfilesystemencoding()
  712. errors = sys.getfilesystemencodeerrors()
  713. def fsencode(filename):
  714. """Encode filename (an os.PathLike, bytes, or str) to the filesystem
  715. encoding with 'surrogateescape' error handler, return bytes unchanged.
  716. On Windows, use 'strict' error handler if the file system encoding is
  717. 'mbcs' (which is the default encoding).
  718. """
  719. filename = fspath(filename) # Does type-checking of `filename`.
  720. if isinstance(filename, str):
  721. return filename.encode(encoding, errors)
  722. else:
  723. return filename
  724. def fsdecode(filename):
  725. """Decode filename (an os.PathLike, bytes, or str) from the filesystem
  726. encoding with 'surrogateescape' error handler, return str unchanged. On
  727. Windows, use 'strict' error handler if the file system encoding is
  728. 'mbcs' (which is the default encoding).
  729. """
  730. filename = fspath(filename) # Does type-checking of `filename`.
  731. if isinstance(filename, bytes):
  732. return filename.decode(encoding, errors)
  733. else:
  734. return filename
  735. return fsencode, fsdecode
  736. fsencode, fsdecode = _fscodec()
  737. del _fscodec
  738. # Supply spawn*() (probably only for Unix)
  739. if _exists("fork") and not _exists("spawnv") and _exists("execv"):
  740. P_WAIT = 0
  741. P_NOWAIT = P_NOWAITO = 1
  742. __all__.extend(["P_WAIT", "P_NOWAIT", "P_NOWAITO"])
  743. # XXX Should we support P_DETACH? I suppose it could fork()**2
  744. # and close the std I/O streams. Also, P_OVERLAY is the same
  745. # as execv*()?
  746. def _spawnvef(mode, file, args, env, func):
  747. # Internal helper; func is the exec*() function to use
  748. if not isinstance(args, (tuple, list)):
  749. raise TypeError('argv must be a tuple or a list')
  750. if not args or not args[0]:
  751. raise ValueError('argv first element cannot be empty')
  752. pid = fork()
  753. if not pid:
  754. # Child
  755. try:
  756. if env is None:
  757. func(file, args)
  758. else:
  759. func(file, args, env)
  760. except:
  761. _exit(127)
  762. else:
  763. # Parent
  764. if mode == P_NOWAIT:
  765. return pid # Caller is responsible for waiting!
  766. while 1:
  767. wpid, sts = waitpid(pid, 0)
  768. if WIFSTOPPED(sts):
  769. continue
  770. return waitstatus_to_exitcode(sts)
  771. def spawnv(mode, file, args):
  772. """spawnv(mode, file, args) -> integer
  773. Execute file with arguments from args in a subprocess.
  774. If mode == P_NOWAIT return the pid of the process.
  775. If mode == P_WAIT return the process's exit code if it exits normally;
  776. otherwise return -SIG, where SIG is the signal that killed it. """
  777. return _spawnvef(mode, file, args, None, execv)
  778. def spawnve(mode, file, args, env):
  779. """spawnve(mode, file, args, env) -> integer
  780. Execute file with arguments from args in a subprocess with the
  781. specified environment.
  782. If mode == P_NOWAIT return the pid of the process.
  783. If mode == P_WAIT return the process's exit code if it exits normally;
  784. otherwise return -SIG, where SIG is the signal that killed it. """
  785. return _spawnvef(mode, file, args, env, execve)
  786. # Note: spawnvp[e] isn't currently supported on Windows
  787. def spawnvp(mode, file, args):
  788. """spawnvp(mode, file, args) -> integer
  789. Execute file (which is looked for along $PATH) with arguments from
  790. args in a subprocess.
  791. If mode == P_NOWAIT return the pid of the process.
  792. If mode == P_WAIT return the process's exit code if it exits normally;
  793. otherwise return -SIG, where SIG is the signal that killed it. """
  794. return _spawnvef(mode, file, args, None, execvp)
  795. def spawnvpe(mode, file, args, env):
  796. """spawnvpe(mode, file, args, env) -> integer
  797. Execute file (which is looked for along $PATH) with arguments from
  798. args in a subprocess with the supplied environment.
  799. If mode == P_NOWAIT return the pid of the process.
  800. If mode == P_WAIT return the process's exit code if it exits normally;
  801. otherwise return -SIG, where SIG is the signal that killed it. """
  802. return _spawnvef(mode, file, args, env, execvpe)
  803. __all__.extend(["spawnv", "spawnve", "spawnvp", "spawnvpe"])
  804. if _exists("spawnv"):
  805. # These aren't supplied by the basic Windows code
  806. # but can be easily implemented in Python
  807. def spawnl(mode, file, *args):
  808. """spawnl(mode, file, *args) -> integer
  809. Execute file with arguments from args in a subprocess.
  810. If mode == P_NOWAIT return the pid of the process.
  811. If mode == P_WAIT return the process's exit code if it exits normally;
  812. otherwise return -SIG, where SIG is the signal that killed it. """
  813. return spawnv(mode, file, args)
  814. def spawnle(mode, file, *args):
  815. """spawnle(mode, file, *args, env) -> integer
  816. Execute file with arguments from args in a subprocess with the
  817. supplied environment.
  818. If mode == P_NOWAIT return the pid of the process.
  819. If mode == P_WAIT return the process's exit code if it exits normally;
  820. otherwise return -SIG, where SIG is the signal that killed it. """
  821. env = args[-1]
  822. return spawnve(mode, file, args[:-1], env)
  823. __all__.extend(["spawnl", "spawnle"])
  824. if _exists("spawnvp"):
  825. # At the moment, Windows doesn't implement spawnvp[e],
  826. # so it won't have spawnlp[e] either.
  827. def spawnlp(mode, file, *args):
  828. """spawnlp(mode, file, *args) -> integer
  829. Execute file (which is looked for along $PATH) with arguments from
  830. args in a subprocess with the supplied environment.
  831. If mode == P_NOWAIT return the pid of the process.
  832. If mode == P_WAIT return the process's exit code if it exits normally;
  833. otherwise return -SIG, where SIG is the signal that killed it. """
  834. return spawnvp(mode, file, args)
  835. def spawnlpe(mode, file, *args):
  836. """spawnlpe(mode, file, *args, env) -> integer
  837. Execute file (which is looked for along $PATH) with arguments from
  838. args in a subprocess with the supplied environment.
  839. If mode == P_NOWAIT return the pid of the process.
  840. If mode == P_WAIT return the process's exit code if it exits normally;
  841. otherwise return -SIG, where SIG is the signal that killed it. """
  842. env = args[-1]
  843. return spawnvpe(mode, file, args[:-1], env)
  844. __all__.extend(["spawnlp", "spawnlpe"])
  845. # VxWorks has no user space shell provided. As a result, running
  846. # command in a shell can't be supported.
  847. if sys.platform != 'vxworks':
  848. # Supply os.popen()
  849. def popen(cmd, mode="r", buffering=-1):
  850. if not isinstance(cmd, str):
  851. raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
  852. if mode not in ("r", "w"):
  853. raise ValueError("invalid mode %r" % mode)
  854. if buffering == 0 or buffering is None:
  855. raise ValueError("popen() does not support unbuffered streams")
  856. import subprocess
  857. if mode == "r":
  858. proc = subprocess.Popen(cmd,
  859. shell=True, text=True,
  860. stdout=subprocess.PIPE,
  861. bufsize=buffering)
  862. return _wrap_close(proc.stdout, proc)
  863. else:
  864. proc = subprocess.Popen(cmd,
  865. shell=True, text=True,
  866. stdin=subprocess.PIPE,
  867. bufsize=buffering)
  868. return _wrap_close(proc.stdin, proc)
  869. # Helper for popen() -- a proxy for a file whose close waits for the process
  870. class _wrap_close:
  871. def __init__(self, stream, proc):
  872. self._stream = stream
  873. self._proc = proc
  874. def close(self):
  875. self._stream.close()
  876. returncode = self._proc.wait()
  877. if returncode == 0:
  878. return None
  879. if name == 'nt':
  880. return returncode
  881. else:
  882. return returncode << 8 # Shift left to match old behavior
  883. def __enter__(self):
  884. return self
  885. def __exit__(self, *args):
  886. self.close()
  887. def __getattr__(self, name):
  888. return getattr(self._stream, name)
  889. def __iter__(self):
  890. return iter(self._stream)
  891. __all__.append("popen")
  892. # Supply os.fdopen()
  893. def fdopen(fd, mode="r", buffering=-1, encoding=None, *args, **kwargs):
  894. if not isinstance(fd, int):
  895. raise TypeError("invalid fd type (%s, expected integer)" % type(fd))
  896. import io
  897. if "b" not in mode:
  898. encoding = io.text_encoding(encoding)
  899. return io.open(fd, mode, buffering, encoding, *args, **kwargs)
  900. # For testing purposes, make sure the function is available when the C
  901. # implementation exists.
  902. def _fspath(path):
  903. """Return the path representation of a path-like object.
  904. If str or bytes is passed in, it is returned unchanged. Otherwise the
  905. os.PathLike interface is used to get the path representation. If the
  906. path representation is not str or bytes, TypeError is raised. If the
  907. provided path is not str, bytes, or os.PathLike, TypeError is raised.
  908. """
  909. if isinstance(path, (str, bytes)):
  910. return path
  911. # Work from the object's type to match method resolution of other magic
  912. # methods.
  913. path_type = type(path)
  914. try:
  915. path_repr = path_type.__fspath__(path)
  916. except AttributeError:
  917. if hasattr(path_type, '__fspath__'):
  918. raise
  919. else:
  920. raise TypeError("expected str, bytes or os.PathLike object, "
  921. "not " + path_type.__name__)
  922. if isinstance(path_repr, (str, bytes)):
  923. return path_repr
  924. else:
  925. raise TypeError("expected {}.__fspath__() to return str or bytes, "
  926. "not {}".format(path_type.__name__,
  927. type(path_repr).__name__))
  928. # If there is no C implementation, make the pure Python version the
  929. # implementation as transparently as possible.
  930. if not _exists('fspath'):
  931. fspath = _fspath
  932. fspath.__name__ = "fspath"
  933. class PathLike(abc.ABC):
  934. """Abstract base class for implementing the file system path protocol."""
  935. @abc.abstractmethod
  936. def __fspath__(self):
  937. """Return the file system path representation of the object."""
  938. raise NotImplementedError
  939. @classmethod
  940. def __subclasshook__(cls, subclass):
  941. if cls is PathLike:
  942. return _check_methods(subclass, '__fspath__')
  943. return NotImplemented
  944. __class_getitem__ = classmethod(GenericAlias)
  945. if name == 'nt':
  946. class _AddedDllDirectory:
  947. def __init__(self, path, cookie, remove_dll_directory):
  948. self.path = path
  949. self._cookie = cookie
  950. self._remove_dll_directory = remove_dll_directory
  951. def close(self):
  952. self._remove_dll_directory(self._cookie)
  953. self.path = None
  954. def __enter__(self):
  955. return self
  956. def __exit__(self, *args):
  957. self.close()
  958. def __repr__(self):
  959. if self.path:
  960. return "<AddedDllDirectory({!r})>".format(self.path)
  961. return "<AddedDllDirectory()>"
  962. def add_dll_directory(path):
  963. """Add a path to the DLL search path.
  964. This search path is used when resolving dependencies for imported
  965. extension modules (the module itself is resolved through sys.path),
  966. and also by ctypes.
  967. Remove the directory by calling close() on the returned object or
  968. using it in a with statement.
  969. """
  970. import nt
  971. cookie = nt._add_dll_directory(path)
  972. return _AddedDllDirectory(
  973. path,
  974. cookie,
  975. nt._remove_dll_directory
  976. )