os.py 38 KB

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