os.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  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. 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 (including symlinks to directories,
  249. and excluding '.' and '..').
  250. filenames is a list of the names of the non-directory files in dirpath.
  251. Note that the names in the lists are just names, with no path components.
  252. To get a full path (which begins with top) to a file or directory in
  253. dirpath, do os.path.join(dirpath, name).
  254. If optional arg 'topdown' is true or not specified, the triple for a
  255. directory is generated before the triples for any of its subdirectories
  256. (directories are generated top down). If topdown is false, the triple
  257. for a directory is generated after the triples for all of its
  258. subdirectories (directories are generated bottom up).
  259. When topdown is true, the caller can modify the dirnames list in-place
  260. (e.g., via del or slice assignment), and walk will only recurse into the
  261. subdirectories whose names remain in dirnames; this can be used to prune the
  262. search, or to impose a specific order of visiting. Modifying dirnames when
  263. topdown is false has no effect on the behavior of os.walk(), since the
  264. directories in dirnames have already been generated by the time dirnames
  265. itself is generated. No matter the value of topdown, the list of
  266. subdirectories is retrieved before the tuples for the directory and its
  267. subdirectories are generated.
  268. By default errors from the os.scandir() call are ignored. If
  269. optional arg 'onerror' is specified, it should be a function; it
  270. will be called with one argument, an OSError instance. It can
  271. report the error to continue with the walk, or raise the exception
  272. to abort the walk. Note that the filename is available as the
  273. filename attribute of the exception object.
  274. By default, os.walk does not follow symbolic links to subdirectories on
  275. systems that support them. In order to get this functionality, set the
  276. optional argument 'followlinks' to true.
  277. Caution: if you pass a relative pathname for top, don't change the
  278. current working directory between resumptions of walk. walk never
  279. changes the current directory, and assumes that the client doesn't
  280. either.
  281. Example:
  282. import os
  283. from os.path import join, getsize
  284. for root, dirs, files in os.walk('python/Lib/email'):
  285. print(root, "consumes ")
  286. print(sum(getsize(join(root, name)) for name in files), end=" ")
  287. print("bytes in", len(files), "non-directory files")
  288. if 'CVS' in dirs:
  289. dirs.remove('CVS') # don't visit CVS directories
  290. """
  291. sys.audit("os.walk", top, topdown, onerror, followlinks)
  292. return _walk(fspath(top), topdown, onerror, followlinks)
  293. def _walk(top, topdown, onerror, followlinks):
  294. dirs = []
  295. nondirs = []
  296. walk_dirs = []
  297. # We may not have read permission for top, in which case we can't
  298. # get a list of the files the directory contains. os.walk
  299. # always suppressed the exception then, rather than blow up for a
  300. # minor reason when (say) a thousand readable directories are still
  301. # left to visit. That logic is copied here.
  302. try:
  303. # Note that scandir is global in this module due
  304. # to earlier import-*.
  305. scandir_it = scandir(top)
  306. except OSError as error:
  307. if onerror is not None:
  308. onerror(error)
  309. return
  310. with scandir_it:
  311. while True:
  312. try:
  313. try:
  314. entry = next(scandir_it)
  315. except StopIteration:
  316. break
  317. except OSError as error:
  318. if onerror is not None:
  319. onerror(error)
  320. return
  321. try:
  322. is_dir = entry.is_dir()
  323. except OSError:
  324. # If is_dir() raises an OSError, consider that the entry is not
  325. # a directory, same behaviour than os.path.isdir().
  326. is_dir = False
  327. if is_dir:
  328. dirs.append(entry.name)
  329. else:
  330. nondirs.append(entry.name)
  331. if not topdown and is_dir:
  332. # Bottom-up: recurse into sub-directory, but exclude symlinks to
  333. # directories if followlinks is False
  334. if followlinks:
  335. walk_into = True
  336. else:
  337. try:
  338. is_symlink = entry.is_symlink()
  339. except OSError:
  340. # If is_symlink() raises an OSError, consider that the
  341. # entry is not a symbolic link, same behaviour than
  342. # os.path.islink().
  343. is_symlink = False
  344. walk_into = not is_symlink
  345. if walk_into:
  346. walk_dirs.append(entry.path)
  347. # Yield before recursion if going top down
  348. if topdown:
  349. yield top, dirs, nondirs
  350. # Recurse into sub-directories
  351. islink, join = path.islink, path.join
  352. for dirname in dirs:
  353. new_path = join(top, dirname)
  354. # Issue #23605: os.path.islink() is used instead of caching
  355. # entry.is_symlink() result during the loop on os.scandir() because
  356. # the caller can replace the directory entry during the "yield"
  357. # above.
  358. if followlinks or not islink(new_path):
  359. yield from _walk(new_path, topdown, onerror, followlinks)
  360. else:
  361. # Recurse into sub-directories
  362. for new_path in walk_dirs:
  363. yield from _walk(new_path, topdown, onerror, followlinks)
  364. # Yield after recursion if going bottom up
  365. yield top, dirs, nondirs
  366. __all__.append("walk")
  367. if {open, stat} <= supports_dir_fd and {scandir, stat} <= supports_fd:
  368. def fwalk(top=".", topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None):
  369. """Directory tree generator.
  370. This behaves exactly like walk(), except that it yields a 4-tuple
  371. dirpath, dirnames, filenames, dirfd
  372. `dirpath`, `dirnames` and `filenames` are identical to walk() output,
  373. and `dirfd` is a file descriptor referring to the directory `dirpath`.
  374. The advantage of fwalk() over walk() is that it's safe against symlink
  375. races (when follow_symlinks is False).
  376. If dir_fd is not None, it should be a file descriptor open to a directory,
  377. and top should be relative; top will then be relative to that directory.
  378. (dir_fd is always supported for fwalk.)
  379. Caution:
  380. Since fwalk() yields file descriptors, those are only valid until the
  381. next iteration step, so you should dup() them if you want to keep them
  382. for a longer period.
  383. Example:
  384. import os
  385. for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
  386. print(root, "consumes", end="")
  387. print(sum(os.stat(name, dir_fd=rootfd).st_size for name in files),
  388. end="")
  389. print("bytes in", len(files), "non-directory files")
  390. if 'CVS' in dirs:
  391. dirs.remove('CVS') # don't visit CVS directories
  392. """
  393. sys.audit("os.fwalk", top, topdown, onerror, follow_symlinks, dir_fd)
  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. formatted_items = ", ".join(
  598. f"{self.decodekey(key)!r}: {self.decodevalue(value)!r}"
  599. for key, value in self._data.items()
  600. )
  601. return f"environ({{{formatted_items}}})"
  602. def copy(self):
  603. return dict(self)
  604. def setdefault(self, key, value):
  605. if key not in self:
  606. self[key] = value
  607. return self[key]
  608. def __ior__(self, other):
  609. self.update(other)
  610. return self
  611. def __or__(self, other):
  612. if not isinstance(other, Mapping):
  613. return NotImplemented
  614. new = dict(self)
  615. new.update(other)
  616. return new
  617. def __ror__(self, other):
  618. if not isinstance(other, Mapping):
  619. return NotImplemented
  620. new = dict(other)
  621. new.update(self)
  622. return new
  623. def _createenviron():
  624. if name == 'nt':
  625. # Where Env Var Names Must Be UPPERCASE
  626. def check_str(value):
  627. if not isinstance(value, str):
  628. raise TypeError("str expected, not %s" % type(value).__name__)
  629. return value
  630. encode = check_str
  631. decode = str
  632. def encodekey(key):
  633. return encode(key).upper()
  634. data = {}
  635. for key, value in environ.items():
  636. data[encodekey(key)] = value
  637. else:
  638. # Where Env Var Names Can Be Mixed Case
  639. encoding = sys.getfilesystemencoding()
  640. def encode(value):
  641. if not isinstance(value, str):
  642. raise TypeError("str expected, not %s" % type(value).__name__)
  643. return value.encode(encoding, 'surrogateescape')
  644. def decode(value):
  645. return value.decode(encoding, 'surrogateescape')
  646. encodekey = encode
  647. data = environ
  648. return _Environ(data,
  649. encodekey, decode,
  650. encode, decode)
  651. # unicode environ
  652. environ = _createenviron()
  653. del _createenviron
  654. def getenv(key, default=None):
  655. """Get an environment variable, return None if it doesn't exist.
  656. The optional second argument can specify an alternate default.
  657. key, default and the result are str."""
  658. return environ.get(key, default)
  659. supports_bytes_environ = (name != 'nt')
  660. __all__.extend(("getenv", "supports_bytes_environ"))
  661. if supports_bytes_environ:
  662. def _check_bytes(value):
  663. if not isinstance(value, bytes):
  664. raise TypeError("bytes expected, not %s" % type(value).__name__)
  665. return value
  666. # bytes environ
  667. environb = _Environ(environ._data,
  668. _check_bytes, bytes,
  669. _check_bytes, bytes)
  670. del _check_bytes
  671. def getenvb(key, default=None):
  672. """Get an environment variable, return None if it doesn't exist.
  673. The optional second argument can specify an alternate default.
  674. key, default and the result are bytes."""
  675. return environb.get(key, default)
  676. __all__.extend(("environb", "getenvb"))
  677. def _fscodec():
  678. encoding = sys.getfilesystemencoding()
  679. errors = sys.getfilesystemencodeerrors()
  680. def fsencode(filename):
  681. """Encode filename (an os.PathLike, bytes, or str) to the filesystem
  682. encoding with 'surrogateescape' error handler, return bytes unchanged.
  683. On Windows, use 'strict' error handler if the file system encoding is
  684. 'mbcs' (which is the default encoding).
  685. """
  686. filename = fspath(filename) # Does type-checking of `filename`.
  687. if isinstance(filename, str):
  688. return filename.encode(encoding, errors)
  689. else:
  690. return filename
  691. def fsdecode(filename):
  692. """Decode filename (an os.PathLike, bytes, or str) from the filesystem
  693. encoding with 'surrogateescape' error handler, return str unchanged. On
  694. Windows, use 'strict' error handler if the file system encoding is
  695. 'mbcs' (which is the default encoding).
  696. """
  697. filename = fspath(filename) # Does type-checking of `filename`.
  698. if isinstance(filename, bytes):
  699. return filename.decode(encoding, errors)
  700. else:
  701. return filename
  702. return fsencode, fsdecode
  703. fsencode, fsdecode = _fscodec()
  704. del _fscodec
  705. # Supply spawn*() (probably only for Unix)
  706. if _exists("fork") and not _exists("spawnv") and _exists("execv"):
  707. P_WAIT = 0
  708. P_NOWAIT = P_NOWAITO = 1
  709. __all__.extend(["P_WAIT", "P_NOWAIT", "P_NOWAITO"])
  710. # XXX Should we support P_DETACH? I suppose it could fork()**2
  711. # and close the std I/O streams. Also, P_OVERLAY is the same
  712. # as execv*()?
  713. def _spawnvef(mode, file, args, env, func):
  714. # Internal helper; func is the exec*() function to use
  715. if not isinstance(args, (tuple, list)):
  716. raise TypeError('argv must be a tuple or a list')
  717. if not args or not args[0]:
  718. raise ValueError('argv first element cannot be empty')
  719. pid = fork()
  720. if not pid:
  721. # Child
  722. try:
  723. if env is None:
  724. func(file, args)
  725. else:
  726. func(file, args, env)
  727. except:
  728. _exit(127)
  729. else:
  730. # Parent
  731. if mode == P_NOWAIT:
  732. return pid # Caller is responsible for waiting!
  733. while 1:
  734. wpid, sts = waitpid(pid, 0)
  735. if WIFSTOPPED(sts):
  736. continue
  737. return waitstatus_to_exitcode(sts)
  738. def spawnv(mode, file, args):
  739. """spawnv(mode, file, args) -> integer
  740. Execute file with arguments from args in a subprocess.
  741. If mode == P_NOWAIT return the pid of the process.
  742. If mode == P_WAIT return the process's exit code if it exits normally;
  743. otherwise return -SIG, where SIG is the signal that killed it. """
  744. return _spawnvef(mode, file, args, None, execv)
  745. def spawnve(mode, file, args, env):
  746. """spawnve(mode, file, args, env) -> integer
  747. Execute file with arguments from args in a subprocess with the
  748. specified environment.
  749. If mode == P_NOWAIT return the pid of the process.
  750. If mode == P_WAIT return the process's exit code if it exits normally;
  751. otherwise return -SIG, where SIG is the signal that killed it. """
  752. return _spawnvef(mode, file, args, env, execve)
  753. # Note: spawnvp[e] isn't currently supported on Windows
  754. def spawnvp(mode, file, args):
  755. """spawnvp(mode, file, args) -> integer
  756. Execute file (which is looked for along $PATH) with arguments from
  757. args in a subprocess.
  758. If mode == P_NOWAIT return the pid of the process.
  759. If mode == P_WAIT return the process's exit code if it exits normally;
  760. otherwise return -SIG, where SIG is the signal that killed it. """
  761. return _spawnvef(mode, file, args, None, execvp)
  762. def spawnvpe(mode, file, args, env):
  763. """spawnvpe(mode, file, args, env) -> integer
  764. Execute file (which is looked for along $PATH) with arguments from
  765. args in a subprocess with the supplied environment.
  766. If mode == P_NOWAIT return the pid of the process.
  767. If mode == P_WAIT return the process's exit code if it exits normally;
  768. otherwise return -SIG, where SIG is the signal that killed it. """
  769. return _spawnvef(mode, file, args, env, execvpe)
  770. __all__.extend(["spawnv", "spawnve", "spawnvp", "spawnvpe"])
  771. if _exists("spawnv"):
  772. # These aren't supplied by the basic Windows code
  773. # but can be easily implemented in Python
  774. def spawnl(mode, file, *args):
  775. """spawnl(mode, file, *args) -> integer
  776. Execute file with arguments from args in a subprocess.
  777. If mode == P_NOWAIT return the pid of the process.
  778. If mode == P_WAIT return the process's exit code if it exits normally;
  779. otherwise return -SIG, where SIG is the signal that killed it. """
  780. return spawnv(mode, file, args)
  781. def spawnle(mode, file, *args):
  782. """spawnle(mode, file, *args, env) -> integer
  783. Execute file with arguments from args in a subprocess with the
  784. supplied environment.
  785. If mode == P_NOWAIT return the pid of the process.
  786. If mode == P_WAIT return the process's exit code if it exits normally;
  787. otherwise return -SIG, where SIG is the signal that killed it. """
  788. env = args[-1]
  789. return spawnve(mode, file, args[:-1], env)
  790. __all__.extend(["spawnl", "spawnle"])
  791. if _exists("spawnvp"):
  792. # At the moment, Windows doesn't implement spawnvp[e],
  793. # so it won't have spawnlp[e] either.
  794. def spawnlp(mode, file, *args):
  795. """spawnlp(mode, file, *args) -> integer
  796. Execute file (which is looked for along $PATH) with arguments from
  797. args in a subprocess with the supplied environment.
  798. If mode == P_NOWAIT return the pid of the process.
  799. If mode == P_WAIT return the process's exit code if it exits normally;
  800. otherwise return -SIG, where SIG is the signal that killed it. """
  801. return spawnvp(mode, file, args)
  802. def spawnlpe(mode, file, *args):
  803. """spawnlpe(mode, file, *args, env) -> integer
  804. Execute file (which is looked for along $PATH) with arguments from
  805. args in a subprocess with the supplied environment.
  806. If mode == P_NOWAIT return the pid of the process.
  807. If mode == P_WAIT return the process's exit code if it exits normally;
  808. otherwise return -SIG, where SIG is the signal that killed it. """
  809. env = args[-1]
  810. return spawnvpe(mode, file, args[:-1], env)
  811. __all__.extend(["spawnlp", "spawnlpe"])
  812. # VxWorks has no user space shell provided. As a result, running
  813. # command in a shell can't be supported.
  814. if sys.platform != 'vxworks':
  815. # Supply os.popen()
  816. def popen(cmd, mode="r", buffering=-1):
  817. if not isinstance(cmd, str):
  818. raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
  819. if mode not in ("r", "w"):
  820. raise ValueError("invalid mode %r" % mode)
  821. if buffering == 0 or buffering is None:
  822. raise ValueError("popen() does not support unbuffered streams")
  823. import subprocess
  824. if mode == "r":
  825. proc = subprocess.Popen(cmd,
  826. shell=True, text=True,
  827. stdout=subprocess.PIPE,
  828. bufsize=buffering)
  829. return _wrap_close(proc.stdout, proc)
  830. else:
  831. proc = subprocess.Popen(cmd,
  832. shell=True, text=True,
  833. stdin=subprocess.PIPE,
  834. bufsize=buffering)
  835. return _wrap_close(proc.stdin, proc)
  836. # Helper for popen() -- a proxy for a file whose close waits for the process
  837. class _wrap_close:
  838. def __init__(self, stream, proc):
  839. self._stream = stream
  840. self._proc = proc
  841. def close(self):
  842. self._stream.close()
  843. returncode = self._proc.wait()
  844. if returncode == 0:
  845. return None
  846. if name == 'nt':
  847. return returncode
  848. else:
  849. return returncode << 8 # Shift left to match old behavior
  850. def __enter__(self):
  851. return self
  852. def __exit__(self, *args):
  853. self.close()
  854. def __getattr__(self, name):
  855. return getattr(self._stream, name)
  856. def __iter__(self):
  857. return iter(self._stream)
  858. __all__.append("popen")
  859. # Supply os.fdopen()
  860. def fdopen(fd, mode="r", buffering=-1, encoding=None, *args, **kwargs):
  861. if not isinstance(fd, int):
  862. raise TypeError("invalid fd type (%s, expected integer)" % type(fd))
  863. import io
  864. if "b" not in mode:
  865. encoding = io.text_encoding(encoding)
  866. return io.open(fd, mode, buffering, encoding, *args, **kwargs)
  867. # For testing purposes, make sure the function is available when the C
  868. # implementation exists.
  869. def _fspath(path):
  870. """Return the path representation of a path-like object.
  871. If str or bytes is passed in, it is returned unchanged. Otherwise the
  872. os.PathLike interface is used to get the path representation. If the
  873. path representation is not str or bytes, TypeError is raised. If the
  874. provided path is not str, bytes, or os.PathLike, TypeError is raised.
  875. """
  876. if isinstance(path, (str, bytes)):
  877. return path
  878. # Work from the object's type to match method resolution of other magic
  879. # methods.
  880. path_type = type(path)
  881. try:
  882. path_repr = path_type.__fspath__(path)
  883. except AttributeError:
  884. if hasattr(path_type, '__fspath__'):
  885. raise
  886. else:
  887. raise TypeError("expected str, bytes or os.PathLike object, "
  888. "not " + path_type.__name__)
  889. if isinstance(path_repr, (str, bytes)):
  890. return path_repr
  891. else:
  892. raise TypeError("expected {}.__fspath__() to return str or bytes, "
  893. "not {}".format(path_type.__name__,
  894. type(path_repr).__name__))
  895. # If there is no C implementation, make the pure Python version the
  896. # implementation as transparently as possible.
  897. if not _exists('fspath'):
  898. fspath = _fspath
  899. fspath.__name__ = "fspath"
  900. class PathLike(abc.ABC):
  901. """Abstract base class for implementing the file system path protocol."""
  902. @abc.abstractmethod
  903. def __fspath__(self):
  904. """Return the file system path representation of the object."""
  905. raise NotImplementedError
  906. @classmethod
  907. def __subclasshook__(cls, subclass):
  908. if cls is PathLike:
  909. return _check_methods(subclass, '__fspath__')
  910. return NotImplemented
  911. __class_getitem__ = classmethod(GenericAlias)
  912. if name == 'nt':
  913. class _AddedDllDirectory:
  914. def __init__(self, path, cookie, remove_dll_directory):
  915. self.path = path
  916. self._cookie = cookie
  917. self._remove_dll_directory = remove_dll_directory
  918. def close(self):
  919. self._remove_dll_directory(self._cookie)
  920. self.path = None
  921. def __enter__(self):
  922. return self
  923. def __exit__(self, *args):
  924. self.close()
  925. def __repr__(self):
  926. if self.path:
  927. return "<AddedDllDirectory({!r})>".format(self.path)
  928. return "<AddedDllDirectory()>"
  929. def add_dll_directory(path):
  930. """Add a path to the DLL search path.
  931. This search path is used when resolving dependencies for imported
  932. extension modules (the module itself is resolved through sys.path),
  933. and also by ctypes.
  934. Remove the directory by calling close() on the returned object or
  935. using it in a with statement.
  936. """
  937. import nt
  938. cookie = nt._add_dll_directory(path)
  939. return _AddedDllDirectory(
  940. path,
  941. cookie,
  942. nt._remove_dll_directory
  943. )