os.py 36 KB

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