io.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. # encoding: utf-8
  2. """
  3. IO related utilities.
  4. """
  5. # Copyright (c) IPython Development Team.
  6. # Distributed under the terms of the Modified BSD License.
  7. import atexit
  8. import os
  9. import sys
  10. import tempfile
  11. from pathlib import Path
  12. from warnings import warn
  13. from IPython.utils.decorators import undoc
  14. from .capture import CapturedIO, capture_output
  15. class Tee(object):
  16. """A class to duplicate an output stream to stdout/err.
  17. This works in a manner very similar to the Unix 'tee' command.
  18. When the object is closed or deleted, it closes the original file given to
  19. it for duplication.
  20. """
  21. # Inspired by:
  22. # http://mail.python.org/pipermail/python-list/2007-May/442737.html
  23. def __init__(self, file_or_name, mode="w", channel='stdout'):
  24. """Construct a new Tee object.
  25. Parameters
  26. ----------
  27. file_or_name : filename or open filehandle (writable)
  28. File that will be duplicated
  29. mode : optional, valid mode for open().
  30. If a filename was give, open with this mode.
  31. channel : str, one of ['stdout', 'stderr']
  32. """
  33. if channel not in ['stdout', 'stderr']:
  34. raise ValueError('Invalid channel spec %s' % channel)
  35. if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):
  36. self.file = file_or_name
  37. else:
  38. encoding = None if "b" in mode else "utf-8"
  39. self.file = open(file_or_name, mode, encoding=encoding)
  40. self.channel = channel
  41. self.ostream = getattr(sys, channel)
  42. setattr(sys, channel, self)
  43. self._closed = False
  44. def close(self):
  45. """Close the file and restore the channel."""
  46. self.flush()
  47. setattr(sys, self.channel, self.ostream)
  48. self.file.close()
  49. self._closed = True
  50. def write(self, data):
  51. """Write data to both channels."""
  52. self.file.write(data)
  53. self.ostream.write(data)
  54. self.ostream.flush()
  55. def flush(self):
  56. """Flush both channels."""
  57. self.file.flush()
  58. self.ostream.flush()
  59. def __del__(self):
  60. if not self._closed:
  61. self.close()
  62. def isatty(self):
  63. return False
  64. def ask_yes_no(prompt, default=None, interrupt=None):
  65. """Asks a question and returns a boolean (y/n) answer.
  66. If default is given (one of 'y','n'), it is used if the user input is
  67. empty. If interrupt is given (one of 'y','n'), it is used if the user
  68. presses Ctrl-C. Otherwise the question is repeated until an answer is
  69. given.
  70. An EOF is treated as the default answer. If there is no default, an
  71. exception is raised to prevent infinite loops.
  72. Valid answers are: y/yes/n/no (match is not case sensitive)."""
  73. answers = {'y':True,'n':False,'yes':True,'no':False}
  74. ans = None
  75. while ans not in answers.keys():
  76. try:
  77. ans = input(prompt+' ').lower()
  78. if not ans: # response was an empty string
  79. ans = default
  80. except KeyboardInterrupt:
  81. if interrupt:
  82. ans = interrupt
  83. print("\r")
  84. except EOFError:
  85. if default in answers.keys():
  86. ans = default
  87. print()
  88. else:
  89. raise
  90. return answers[ans]
  91. def temp_pyfile(src, ext='.py'):
  92. """Make a temporary python file, return filename and filehandle.
  93. Parameters
  94. ----------
  95. src : string or list of strings (no need for ending newlines if list)
  96. Source code to be written to the file.
  97. ext : optional, string
  98. Extension for the generated file.
  99. Returns
  100. -------
  101. (filename, open filehandle)
  102. It is the caller's responsibility to close the open file and unlink it.
  103. """
  104. fname = tempfile.mkstemp(ext)[1]
  105. with open(Path(fname), "w", encoding="utf-8") as f:
  106. f.write(src)
  107. f.flush()
  108. return fname
  109. @undoc
  110. def raw_print(*args, **kw):
  111. """DEPRECATED: Raw print to sys.__stdout__, otherwise identical interface to print()."""
  112. warn("IPython.utils.io.raw_print has been deprecated since IPython 7.0", DeprecationWarning, stacklevel=2)
  113. print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
  114. file=sys.__stdout__)
  115. sys.__stdout__.flush()
  116. @undoc
  117. def raw_print_err(*args, **kw):
  118. """DEPRECATED: Raw print to sys.__stderr__, otherwise identical interface to print()."""
  119. warn("IPython.utils.io.raw_print_err has been deprecated since IPython 7.0", DeprecationWarning, stacklevel=2)
  120. print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
  121. file=sys.__stderr__)
  122. sys.__stderr__.flush()