1
0

_compat.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. # flake8: noqa
  2. import codecs
  3. import io
  4. import os
  5. import re
  6. import sys
  7. from weakref import WeakKeyDictionary
  8. PY2 = sys.version_info[0] == 2
  9. CYGWIN = sys.platform.startswith("cygwin")
  10. MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)
  11. # Determine local App Engine environment, per Google's own suggestion
  12. APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(
  13. "SERVER_SOFTWARE", ""
  14. )
  15. WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS2
  16. DEFAULT_COLUMNS = 80
  17. _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")
  18. def get_filesystem_encoding():
  19. return sys.getfilesystemencoding() or sys.getdefaultencoding()
  20. def _make_text_stream(
  21. stream, encoding, errors, force_readable=False, force_writable=False
  22. ):
  23. if encoding is None:
  24. encoding = get_best_encoding(stream)
  25. if errors is None:
  26. errors = "replace"
  27. return _NonClosingTextIOWrapper(
  28. stream,
  29. encoding,
  30. errors,
  31. line_buffering=True,
  32. force_readable=force_readable,
  33. force_writable=force_writable,
  34. )
  35. def is_ascii_encoding(encoding):
  36. """Checks if a given encoding is ascii."""
  37. try:
  38. return codecs.lookup(encoding).name == "ascii"
  39. except LookupError:
  40. return False
  41. def get_best_encoding(stream):
  42. """Returns the default stream encoding if not found."""
  43. rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()
  44. if is_ascii_encoding(rv):
  45. return "utf-8"
  46. return rv
  47. class _NonClosingTextIOWrapper(io.TextIOWrapper):
  48. def __init__(
  49. self,
  50. stream,
  51. encoding,
  52. errors,
  53. force_readable=False,
  54. force_writable=False,
  55. **extra
  56. ):
  57. self._stream = stream = _FixupStream(stream, force_readable, force_writable)
  58. io.TextIOWrapper.__init__(self, stream, encoding, errors, **extra)
  59. # The io module is a place where the Python 3 text behavior
  60. # was forced upon Python 2, so we need to unbreak
  61. # it to look like Python 2.
  62. if PY2:
  63. def write(self, x):
  64. if isinstance(x, str) or is_bytes(x):
  65. try:
  66. self.flush()
  67. except Exception:
  68. pass
  69. return self.buffer.write(str(x))
  70. return io.TextIOWrapper.write(self, x)
  71. def writelines(self, lines):
  72. for line in lines:
  73. self.write(line)
  74. def __del__(self):
  75. try:
  76. self.detach()
  77. except Exception:
  78. pass
  79. def isatty(self):
  80. # https://bitbucket.org/pypy/pypy/issue/1803
  81. return self._stream.isatty()
  82. class _FixupStream(object):
  83. """The new io interface needs more from streams than streams
  84. traditionally implement. As such, this fix-up code is necessary in
  85. some circumstances.
  86. The forcing of readable and writable flags are there because some tools
  87. put badly patched objects on sys (one such offender are certain version
  88. of jupyter notebook).
  89. """
  90. def __init__(self, stream, force_readable=False, force_writable=False):
  91. self._stream = stream
  92. self._force_readable = force_readable
  93. self._force_writable = force_writable
  94. def __getattr__(self, name):
  95. return getattr(self._stream, name)
  96. def read1(self, size):
  97. f = getattr(self._stream, "read1", None)
  98. if f is not None:
  99. return f(size)
  100. # We only dispatch to readline instead of read in Python 2 as we
  101. # do not want cause problems with the different implementation
  102. # of line buffering.
  103. if PY2:
  104. return self._stream.readline(size)
  105. return self._stream.read(size)
  106. def readable(self):
  107. if self._force_readable:
  108. return True
  109. x = getattr(self._stream, "readable", None)
  110. if x is not None:
  111. return x()
  112. try:
  113. self._stream.read(0)
  114. except Exception:
  115. return False
  116. return True
  117. def writable(self):
  118. if self._force_writable:
  119. return True
  120. x = getattr(self._stream, "writable", None)
  121. if x is not None:
  122. return x()
  123. try:
  124. self._stream.write("")
  125. except Exception:
  126. try:
  127. self._stream.write(b"")
  128. except Exception:
  129. return False
  130. return True
  131. def seekable(self):
  132. x = getattr(self._stream, "seekable", None)
  133. if x is not None:
  134. return x()
  135. try:
  136. self._stream.seek(self._stream.tell())
  137. except Exception:
  138. return False
  139. return True
  140. if PY2:
  141. text_type = unicode
  142. raw_input = raw_input
  143. string_types = (str, unicode)
  144. int_types = (int, long)
  145. iteritems = lambda x: x.iteritems()
  146. range_type = xrange
  147. def is_bytes(x):
  148. return isinstance(x, (buffer, bytearray))
  149. _identifier_re = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
  150. # For Windows, we need to force stdout/stdin/stderr to binary if it's
  151. # fetched for that. This obviously is not the most correct way to do
  152. # it as it changes global state. Unfortunately, there does not seem to
  153. # be a clear better way to do it as just reopening the file in binary
  154. # mode does not change anything.
  155. #
  156. # An option would be to do what Python 3 does and to open the file as
  157. # binary only, patch it back to the system, and then use a wrapper
  158. # stream that converts newlines. It's not quite clear what's the
  159. # correct option here.
  160. #
  161. # This code also lives in _winconsole for the fallback to the console
  162. # emulation stream.
  163. #
  164. # There are also Windows environments where the `msvcrt` module is not
  165. # available (which is why we use try-catch instead of the WIN variable
  166. # here), such as the Google App Engine development server on Windows. In
  167. # those cases there is just nothing we can do.
  168. def set_binary_mode(f):
  169. return f
  170. try:
  171. import msvcrt
  172. except ImportError:
  173. pass
  174. else:
  175. def set_binary_mode(f):
  176. try:
  177. fileno = f.fileno()
  178. except Exception:
  179. pass
  180. else:
  181. msvcrt.setmode(fileno, os.O_BINARY)
  182. return f
  183. try:
  184. import fcntl
  185. except ImportError:
  186. pass
  187. else:
  188. def set_binary_mode(f):
  189. try:
  190. fileno = f.fileno()
  191. except Exception:
  192. pass
  193. else:
  194. flags = fcntl.fcntl(fileno, fcntl.F_GETFL)
  195. fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)
  196. return f
  197. def isidentifier(x):
  198. return _identifier_re.search(x) is not None
  199. def get_binary_stdin():
  200. return set_binary_mode(sys.stdin)
  201. def get_binary_stdout():
  202. _wrap_std_stream("stdout")
  203. return set_binary_mode(sys.stdout)
  204. def get_binary_stderr():
  205. _wrap_std_stream("stderr")
  206. return set_binary_mode(sys.stderr)
  207. def get_text_stdin(encoding=None, errors=None):
  208. rv = _get_windows_console_stream(sys.stdin, encoding, errors)
  209. if rv is not None:
  210. return rv
  211. return _make_text_stream(sys.stdin, encoding, errors, force_readable=True)
  212. def get_text_stdout(encoding=None, errors=None):
  213. _wrap_std_stream("stdout")
  214. rv = _get_windows_console_stream(sys.stdout, encoding, errors)
  215. if rv is not None:
  216. return rv
  217. return _make_text_stream(sys.stdout, encoding, errors, force_writable=True)
  218. def get_text_stderr(encoding=None, errors=None):
  219. _wrap_std_stream("stderr")
  220. rv = _get_windows_console_stream(sys.stderr, encoding, errors)
  221. if rv is not None:
  222. return rv
  223. return _make_text_stream(sys.stderr, encoding, errors, force_writable=True)
  224. def filename_to_ui(value):
  225. if isinstance(value, bytes):
  226. value = value.decode(get_filesystem_encoding(), "replace")
  227. return value
  228. else:
  229. import io
  230. text_type = str
  231. raw_input = input
  232. string_types = (str,)
  233. int_types = (int,)
  234. range_type = range
  235. isidentifier = lambda x: x.isidentifier()
  236. iteritems = lambda x: iter(x.items())
  237. def is_bytes(x):
  238. return isinstance(x, (bytes, memoryview, bytearray))
  239. def _is_binary_reader(stream, default=False):
  240. try:
  241. return isinstance(stream.read(0), bytes)
  242. except Exception:
  243. return default
  244. # This happens in some cases where the stream was already
  245. # closed. In this case, we assume the default.
  246. def _is_binary_writer(stream, default=False):
  247. try:
  248. stream.write(b"")
  249. except Exception:
  250. try:
  251. stream.write("")
  252. return False
  253. except Exception:
  254. pass
  255. return default
  256. return True
  257. def _find_binary_reader(stream):
  258. # We need to figure out if the given stream is already binary.
  259. # This can happen because the official docs recommend detaching
  260. # the streams to get binary streams. Some code might do this, so
  261. # we need to deal with this case explicitly.
  262. if _is_binary_reader(stream, False):
  263. return stream
  264. buf = getattr(stream, "buffer", None)
  265. # Same situation here; this time we assume that the buffer is
  266. # actually binary in case it's closed.
  267. if buf is not None and _is_binary_reader(buf, True):
  268. return buf
  269. def _find_binary_writer(stream):
  270. # We need to figure out if the given stream is already binary.
  271. # This can happen because the official docs recommend detatching
  272. # the streams to get binary streams. Some code might do this, so
  273. # we need to deal with this case explicitly.
  274. if _is_binary_writer(stream, False):
  275. return stream
  276. buf = getattr(stream, "buffer", None)
  277. # Same situation here; this time we assume that the buffer is
  278. # actually binary in case it's closed.
  279. if buf is not None and _is_binary_writer(buf, True):
  280. return buf
  281. def _stream_is_misconfigured(stream):
  282. """A stream is misconfigured if its encoding is ASCII."""
  283. # If the stream does not have an encoding set, we assume it's set
  284. # to ASCII. This appears to happen in certain unittest
  285. # environments. It's not quite clear what the correct behavior is
  286. # but this at least will force Click to recover somehow.
  287. return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")
  288. def _is_compat_stream_attr(stream, attr, value):
  289. """A stream attribute is compatible if it is equal to the
  290. desired value or the desired value is unset and the attribute
  291. has a value.
  292. """
  293. stream_value = getattr(stream, attr, None)
  294. return stream_value == value or (value is None and stream_value is not None)
  295. def _is_compatible_text_stream(stream, encoding, errors):
  296. """Check if a stream's encoding and errors attributes are
  297. compatible with the desired values.
  298. """
  299. return _is_compat_stream_attr(
  300. stream, "encoding", encoding
  301. ) and _is_compat_stream_attr(stream, "errors", errors)
  302. def _force_correct_text_stream(
  303. text_stream,
  304. encoding,
  305. errors,
  306. is_binary,
  307. find_binary,
  308. force_readable=False,
  309. force_writable=False,
  310. ):
  311. if is_binary(text_stream, False):
  312. binary_reader = text_stream
  313. else:
  314. # If the stream looks compatible, and won't default to a
  315. # misconfigured ascii encoding, return it as-is.
  316. if _is_compatible_text_stream(text_stream, encoding, errors) and not (
  317. encoding is None and _stream_is_misconfigured(text_stream)
  318. ):
  319. return text_stream
  320. # Otherwise, get the underlying binary reader.
  321. binary_reader = find_binary(text_stream)
  322. # If that's not possible, silently use the original reader
  323. # and get mojibake instead of exceptions.
  324. if binary_reader is None:
  325. return text_stream
  326. # Default errors to replace instead of strict in order to get
  327. # something that works.
  328. if errors is None:
  329. errors = "replace"
  330. # Wrap the binary stream in a text stream with the correct
  331. # encoding parameters.
  332. return _make_text_stream(
  333. binary_reader,
  334. encoding,
  335. errors,
  336. force_readable=force_readable,
  337. force_writable=force_writable,
  338. )
  339. def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):
  340. return _force_correct_text_stream(
  341. text_reader,
  342. encoding,
  343. errors,
  344. _is_binary_reader,
  345. _find_binary_reader,
  346. force_readable=force_readable,
  347. )
  348. def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):
  349. return _force_correct_text_stream(
  350. text_writer,
  351. encoding,
  352. errors,
  353. _is_binary_writer,
  354. _find_binary_writer,
  355. force_writable=force_writable,
  356. )
  357. def get_binary_stdin():
  358. reader = _find_binary_reader(sys.stdin)
  359. if reader is None:
  360. raise RuntimeError("Was not able to determine binary stream for sys.stdin.")
  361. return reader
  362. def get_binary_stdout():
  363. writer = _find_binary_writer(sys.stdout)
  364. if writer is None:
  365. raise RuntimeError(
  366. "Was not able to determine binary stream for sys.stdout."
  367. )
  368. return writer
  369. def get_binary_stderr():
  370. writer = _find_binary_writer(sys.stderr)
  371. if writer is None:
  372. raise RuntimeError(
  373. "Was not able to determine binary stream for sys.stderr."
  374. )
  375. return writer
  376. def get_text_stdin(encoding=None, errors=None):
  377. rv = _get_windows_console_stream(sys.stdin, encoding, errors)
  378. if rv is not None:
  379. return rv
  380. return _force_correct_text_reader(
  381. sys.stdin, encoding, errors, force_readable=True
  382. )
  383. def get_text_stdout(encoding=None, errors=None):
  384. rv = _get_windows_console_stream(sys.stdout, encoding, errors)
  385. if rv is not None:
  386. return rv
  387. return _force_correct_text_writer(
  388. sys.stdout, encoding, errors, force_writable=True
  389. )
  390. def get_text_stderr(encoding=None, errors=None):
  391. rv = _get_windows_console_stream(sys.stderr, encoding, errors)
  392. if rv is not None:
  393. return rv
  394. return _force_correct_text_writer(
  395. sys.stderr, encoding, errors, force_writable=True
  396. )
  397. def filename_to_ui(value):
  398. if isinstance(value, bytes):
  399. value = value.decode(get_filesystem_encoding(), "replace")
  400. else:
  401. value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace")
  402. return value
  403. def get_streerror(e, default=None):
  404. if hasattr(e, "strerror"):
  405. msg = e.strerror
  406. else:
  407. if default is not None:
  408. msg = default
  409. else:
  410. msg = str(e)
  411. if isinstance(msg, bytes):
  412. msg = msg.decode("utf-8", "replace")
  413. return msg
  414. def _wrap_io_open(file, mode, encoding, errors):
  415. """On Python 2, :func:`io.open` returns a text file wrapper that
  416. requires passing ``unicode`` to ``write``. Need to open the file in
  417. binary mode then wrap it in a subclass that can write ``str`` and
  418. ``unicode``.
  419. Also handles not passing ``encoding`` and ``errors`` in binary mode.
  420. """
  421. binary = "b" in mode
  422. if binary:
  423. kwargs = {}
  424. else:
  425. kwargs = {"encoding": encoding, "errors": errors}
  426. if not PY2 or binary:
  427. return io.open(file, mode, **kwargs)
  428. f = io.open(file, "{}b".format(mode.replace("t", "")))
  429. return _make_text_stream(f, **kwargs)
  430. def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):
  431. binary = "b" in mode
  432. # Standard streams first. These are simple because they don't need
  433. # special handling for the atomic flag. It's entirely ignored.
  434. if filename == "-":
  435. if any(m in mode for m in ["w", "a", "x"]):
  436. if binary:
  437. return get_binary_stdout(), False
  438. return get_text_stdout(encoding=encoding, errors=errors), False
  439. if binary:
  440. return get_binary_stdin(), False
  441. return get_text_stdin(encoding=encoding, errors=errors), False
  442. # Non-atomic writes directly go out through the regular open functions.
  443. if not atomic:
  444. return _wrap_io_open(filename, mode, encoding, errors), True
  445. # Some usability stuff for atomic writes
  446. if "a" in mode:
  447. raise ValueError(
  448. "Appending to an existing file is not supported, because that"
  449. " would involve an expensive `copy`-operation to a temporary"
  450. " file. Open the file in normal `w`-mode and copy explicitly"
  451. " if that's what you're after."
  452. )
  453. if "x" in mode:
  454. raise ValueError("Use the `overwrite`-parameter instead.")
  455. if "w" not in mode:
  456. raise ValueError("Atomic writes only make sense with `w`-mode.")
  457. # Atomic writes are more complicated. They work by opening a file
  458. # as a proxy in the same folder and then using the fdopen
  459. # functionality to wrap it in a Python file. Then we wrap it in an
  460. # atomic file that moves the file over on close.
  461. import errno
  462. import random
  463. try:
  464. perm = os.stat(filename).st_mode
  465. except OSError:
  466. perm = None
  467. flags = os.O_RDWR | os.O_CREAT | os.O_EXCL
  468. if binary:
  469. flags |= getattr(os, "O_BINARY", 0)
  470. while True:
  471. tmp_filename = os.path.join(
  472. os.path.dirname(filename),
  473. ".__atomic-write{:08x}".format(random.randrange(1 << 32)),
  474. )
  475. try:
  476. fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)
  477. break
  478. except OSError as e:
  479. if e.errno == errno.EEXIST or (
  480. os.name == "nt"
  481. and e.errno == errno.EACCES
  482. and os.path.isdir(e.filename)
  483. and os.access(e.filename, os.W_OK)
  484. ):
  485. continue
  486. raise
  487. if perm is not None:
  488. os.chmod(tmp_filename, perm) # in case perm includes bits in umask
  489. f = _wrap_io_open(fd, mode, encoding, errors)
  490. return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True
  491. # Used in a destructor call, needs extra protection from interpreter cleanup.
  492. if hasattr(os, "replace"):
  493. _replace = os.replace
  494. _can_replace = True
  495. else:
  496. _replace = os.rename
  497. _can_replace = not WIN
  498. class _AtomicFile(object):
  499. def __init__(self, f, tmp_filename, real_filename):
  500. self._f = f
  501. self._tmp_filename = tmp_filename
  502. self._real_filename = real_filename
  503. self.closed = False
  504. @property
  505. def name(self):
  506. return self._real_filename
  507. def close(self, delete=False):
  508. if self.closed:
  509. return
  510. self._f.close()
  511. if not _can_replace:
  512. try:
  513. os.remove(self._real_filename)
  514. except OSError:
  515. pass
  516. _replace(self._tmp_filename, self._real_filename)
  517. self.closed = True
  518. def __getattr__(self, name):
  519. return getattr(self._f, name)
  520. def __enter__(self):
  521. return self
  522. def __exit__(self, exc_type, exc_value, tb):
  523. self.close(delete=exc_type is not None)
  524. def __repr__(self):
  525. return repr(self._f)
  526. auto_wrap_for_ansi = None
  527. colorama = None
  528. get_winterm_size = None
  529. def strip_ansi(value):
  530. return _ansi_re.sub("", value)
  531. def _is_jupyter_kernel_output(stream):
  532. if WIN:
  533. # TODO: Couldn't test on Windows, should't try to support until
  534. # someone tests the details wrt colorama.
  535. return
  536. while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):
  537. stream = stream._stream
  538. return stream.__class__.__module__.startswith("ipykernel.")
  539. def should_strip_ansi(stream=None, color=None):
  540. if color is None:
  541. if stream is None:
  542. stream = sys.stdin
  543. return not isatty(stream) and not _is_jupyter_kernel_output(stream)
  544. return not color
  545. # If we're on Windows, we provide transparent integration through
  546. # colorama. This will make ANSI colors through the echo function
  547. # work automatically.
  548. if WIN:
  549. # Windows has a smaller terminal
  550. DEFAULT_COLUMNS = 79
  551. from ._winconsole import _get_windows_console_stream, _wrap_std_stream
  552. def _get_argv_encoding():
  553. import locale
  554. return locale.getpreferredencoding()
  555. if PY2:
  556. def raw_input(prompt=""):
  557. sys.stderr.flush()
  558. if prompt:
  559. stdout = _default_text_stdout()
  560. stdout.write(prompt)
  561. stdin = _default_text_stdin()
  562. return stdin.readline().rstrip("\r\n")
  563. try:
  564. import colorama
  565. except ImportError:
  566. pass
  567. else:
  568. _ansi_stream_wrappers = WeakKeyDictionary()
  569. def auto_wrap_for_ansi(stream, color=None):
  570. """This function wraps a stream so that calls through colorama
  571. are issued to the win32 console API to recolor on demand. It
  572. also ensures to reset the colors if a write call is interrupted
  573. to not destroy the console afterwards.
  574. """
  575. try:
  576. cached = _ansi_stream_wrappers.get(stream)
  577. except Exception:
  578. cached = None
  579. if cached is not None:
  580. return cached
  581. strip = should_strip_ansi(stream, color)
  582. ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)
  583. rv = ansi_wrapper.stream
  584. _write = rv.write
  585. def _safe_write(s):
  586. try:
  587. return _write(s)
  588. except:
  589. ansi_wrapper.reset_all()
  590. raise
  591. rv.write = _safe_write
  592. try:
  593. _ansi_stream_wrappers[stream] = rv
  594. except Exception:
  595. pass
  596. return rv
  597. def get_winterm_size():
  598. win = colorama.win32.GetConsoleScreenBufferInfo(
  599. colorama.win32.STDOUT
  600. ).srWindow
  601. return win.Right - win.Left, win.Bottom - win.Top
  602. else:
  603. def _get_argv_encoding():
  604. return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()
  605. _get_windows_console_stream = lambda *x: None
  606. _wrap_std_stream = lambda *x: None
  607. def term_len(x):
  608. return len(strip_ansi(x))
  609. def isatty(stream):
  610. try:
  611. return stream.isatty()
  612. except Exception:
  613. return False
  614. def _make_cached_stream_func(src_func, wrapper_func):
  615. cache = WeakKeyDictionary()
  616. def func():
  617. stream = src_func()
  618. try:
  619. rv = cache.get(stream)
  620. except Exception:
  621. rv = None
  622. if rv is not None:
  623. return rv
  624. rv = wrapper_func()
  625. try:
  626. stream = src_func() # In case wrapper_func() modified the stream
  627. cache[stream] = rv
  628. except Exception:
  629. pass
  630. return rv
  631. return func
  632. _default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)
  633. _default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)
  634. _default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)
  635. binary_streams = {
  636. "stdin": get_binary_stdin,
  637. "stdout": get_binary_stdout,
  638. "stderr": get_binary_stderr,
  639. }
  640. text_streams = {
  641. "stdin": get_text_stdin,
  642. "stdout": get_text_stdout,
  643. "stderr": get_text_stderr,
  644. }