os.py 38 KB

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