os.py 39 KB

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