io.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # coding: utf-8
  2. """io-related utilities"""
  3. # Copyright (c) Jupyter Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. import codecs
  6. import sys
  7. from ipython_genutils.py3compat import PY3
  8. def unicode_std_stream(stream='stdout'):
  9. u"""Get a wrapper to write unicode to stdout/stderr as UTF-8.
  10. This ignores environment variables and default encodings, to reliably write
  11. unicode to stdout or stderr.
  12. ::
  13. unicode_std_stream().write(u'ł@e¶ŧ←')
  14. """
  15. assert stream in ('stdout', 'stderr')
  16. stream = getattr(sys, stream)
  17. if PY3:
  18. try:
  19. stream_b = stream.buffer
  20. except AttributeError:
  21. # sys.stdout has been replaced - use it directly
  22. return stream
  23. else:
  24. stream_b = stream
  25. return codecs.getwriter('utf-8')(stream_b)
  26. def unicode_stdin_stream():
  27. u"""Get a wrapper to read unicode from stdin as UTF-8.
  28. This ignores environment variables and default encodings, to reliably read unicode from stdin.
  29. ::
  30. totreat = unicode_stdin_stream().read()
  31. """
  32. stream = sys.stdin
  33. if PY3:
  34. try:
  35. stream_b = stream.buffer
  36. except AttributeError:
  37. return stream
  38. else:
  39. stream_b = stream
  40. return codecs.getreader('utf-8')(stream_b)