PageRenderTime 26ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/IPython/utils/io.py

https://github.com/cboos/ipython
Python | 321 lines | 246 code | 25 blank | 50 comment | 15 complexity | 474b480a13d1a6f0d2f678a3a688032d MD5 | raw file
  1. # encoding: utf-8
  2. """
  3. IO related utilities.
  4. """
  5. #-----------------------------------------------------------------------------
  6. # Copyright (C) 2008-2011 The IPython Development Team
  7. #
  8. # Distributed under the terms of the BSD License. The full license is in
  9. # the file COPYING, distributed as part of this software.
  10. #-----------------------------------------------------------------------------
  11. from __future__ import print_function
  12. #-----------------------------------------------------------------------------
  13. # Imports
  14. #-----------------------------------------------------------------------------
  15. import sys
  16. import tempfile
  17. #-----------------------------------------------------------------------------
  18. # Code
  19. #-----------------------------------------------------------------------------
  20. class IOStream:
  21. def __init__(self,stream, fallback=None):
  22. if not hasattr(stream,'write') or not hasattr(stream,'flush'):
  23. if fallback is not None:
  24. stream = fallback
  25. else:
  26. raise ValueError("fallback required, but not specified")
  27. self.stream = stream
  28. self._swrite = stream.write
  29. # clone all methods not overridden:
  30. def clone(meth):
  31. return not hasattr(self, meth) and not meth.startswith('_')
  32. for meth in filter(clone, dir(stream)):
  33. setattr(self, meth, getattr(stream, meth))
  34. def write(self,data):
  35. try:
  36. self._swrite(data)
  37. except:
  38. try:
  39. # print handles some unicode issues which may trip a plain
  40. # write() call. Emulate write() by using an empty end
  41. # argument.
  42. print(data, end='', file=self.stream)
  43. except:
  44. # if we get here, something is seriously broken.
  45. print('ERROR - failed to write data to stream:', self.stream,
  46. file=sys.stderr)
  47. def writelines(self, lines):
  48. if isinstance(lines, basestring):
  49. lines = [lines]
  50. for line in lines:
  51. self.write(line)
  52. # This class used to have a writeln method, but regular files and streams
  53. # in Python don't have this method. We need to keep this completely
  54. # compatible so we removed it.
  55. @property
  56. def closed(self):
  57. return self.stream.closed
  58. def close(self):
  59. pass
  60. class IOTerm:
  61. """ Term holds the file or file-like objects for handling I/O operations.
  62. These are normally just sys.stdin, sys.stdout and sys.stderr but for
  63. Windows they can can replaced to allow editing the strings before they are
  64. displayed."""
  65. # In the future, having IPython channel all its I/O operations through
  66. # this class will make it easier to embed it into other environments which
  67. # are not a normal terminal (such as a GUI-based shell)
  68. def __init__(self, stdin=None, stdout=None, stderr=None):
  69. self.stdin = IOStream(stdin, sys.stdin)
  70. self.stdout = IOStream(stdout, sys.stdout)
  71. self.stderr = IOStream(stderr, sys.stderr)
  72. # setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
  73. stdin = IOStream(sys.stdin)
  74. stdout = IOStream(sys.stdout)
  75. stderr = IOStream(sys.stderr)
  76. class Tee(object):
  77. """A class to duplicate an output stream to stdout/err.
  78. This works in a manner very similar to the Unix 'tee' command.
  79. When the object is closed or deleted, it closes the original file given to
  80. it for duplication.
  81. """
  82. # Inspired by:
  83. # http://mail.python.org/pipermail/python-list/2007-May/442737.html
  84. def __init__(self, file_or_name, mode="w", channel='stdout'):
  85. """Construct a new Tee object.
  86. Parameters
  87. ----------
  88. file_or_name : filename or open filehandle (writable)
  89. File that will be duplicated
  90. mode : optional, valid mode for open().
  91. If a filename was give, open with this mode.
  92. channel : str, one of ['stdout', 'stderr']
  93. """
  94. if channel not in ['stdout', 'stderr']:
  95. raise ValueError('Invalid channel spec %s' % channel)
  96. if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):
  97. self.file = file_or_name
  98. else:
  99. self.file = open(file_or_name, mode)
  100. self.channel = channel
  101. self.ostream = getattr(sys, channel)
  102. setattr(sys, channel, self)
  103. self._closed = False
  104. def close(self):
  105. """Close the file and restore the channel."""
  106. self.flush()
  107. setattr(sys, self.channel, self.ostream)
  108. self.file.close()
  109. self._closed = True
  110. def write(self, data):
  111. """Write data to both channels."""
  112. self.file.write(data)
  113. self.ostream.write(data)
  114. self.ostream.flush()
  115. def flush(self):
  116. """Flush both channels."""
  117. self.file.flush()
  118. self.ostream.flush()
  119. def __del__(self):
  120. if not self._closed:
  121. self.close()
  122. def file_read(filename):
  123. """Read a file and close it. Returns the file source."""
  124. fobj = open(filename,'r');
  125. source = fobj.read();
  126. fobj.close()
  127. return source
  128. def file_readlines(filename):
  129. """Read a file and close it. Returns the file source using readlines()."""
  130. fobj = open(filename,'r');
  131. lines = fobj.readlines();
  132. fobj.close()
  133. return lines
  134. def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
  135. """Take multiple lines of input.
  136. A list with each line of input as a separate element is returned when a
  137. termination string is entered (defaults to a single '.'). Input can also
  138. terminate via EOF (^D in Unix, ^Z-RET in Windows).
  139. Lines of input which end in \\ are joined into single entries (and a
  140. secondary continuation prompt is issued as long as the user terminates
  141. lines with \\). This allows entering very long strings which are still
  142. meant to be treated as single entities.
  143. """
  144. try:
  145. if header:
  146. header += '\n'
  147. lines = [raw_input(header + ps1)]
  148. except EOFError:
  149. return []
  150. terminate = [terminate_str]
  151. try:
  152. while lines[-1:] != terminate:
  153. new_line = raw_input(ps1)
  154. while new_line.endswith('\\'):
  155. new_line = new_line[:-1] + raw_input(ps2)
  156. lines.append(new_line)
  157. return lines[:-1] # don't return the termination command
  158. except EOFError:
  159. print()
  160. return lines
  161. def raw_input_ext(prompt='', ps2='... '):
  162. """Similar to raw_input(), but accepts extended lines if input ends with \\."""
  163. line = raw_input(prompt)
  164. while line.endswith('\\'):
  165. line = line[:-1] + raw_input(ps2)
  166. return line
  167. def ask_yes_no(prompt,default=None):
  168. """Asks a question and returns a boolean (y/n) answer.
  169. If default is given (one of 'y','n'), it is used if the user input is
  170. empty. Otherwise the question is repeated until an answer is given.
  171. An EOF is treated as the default answer. If there is no default, an
  172. exception is raised to prevent infinite loops.
  173. Valid answers are: y/yes/n/no (match is not case sensitive)."""
  174. answers = {'y':True,'n':False,'yes':True,'no':False}
  175. ans = None
  176. while ans not in answers.keys():
  177. try:
  178. ans = raw_input(prompt+' ').lower()
  179. if not ans: # response was an empty string
  180. ans = default
  181. except KeyboardInterrupt:
  182. pass
  183. except EOFError:
  184. if default in answers.keys():
  185. ans = default
  186. print()
  187. else:
  188. raise
  189. return answers[ans]
  190. class NLprinter:
  191. """Print an arbitrarily nested list, indicating index numbers.
  192. An instance of this class called nlprint is available and callable as a
  193. function.
  194. nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
  195. and using 'sep' to separate the index from the value. """
  196. def __init__(self):
  197. self.depth = 0
  198. def __call__(self,lst,pos='',**kw):
  199. """Prints the nested list numbering levels."""
  200. kw.setdefault('indent',' ')
  201. kw.setdefault('sep',': ')
  202. kw.setdefault('start',0)
  203. kw.setdefault('stop',len(lst))
  204. # we need to remove start and stop from kw so they don't propagate
  205. # into a recursive call for a nested list.
  206. start = kw['start']; del kw['start']
  207. stop = kw['stop']; del kw['stop']
  208. if self.depth == 0 and 'header' in kw.keys():
  209. print(kw['header'])
  210. for idx in range(start,stop):
  211. elem = lst[idx]
  212. newpos = pos + str(idx)
  213. if type(elem)==type([]):
  214. self.depth += 1
  215. self.__call__(elem, newpos+",", **kw)
  216. self.depth -= 1
  217. else:
  218. print(kw['indent']*self.depth + newpos + kw["sep"] + repr(elem))
  219. nlprint = NLprinter()
  220. def temp_pyfile(src, ext='.py'):
  221. """Make a temporary python file, return filename and filehandle.
  222. Parameters
  223. ----------
  224. src : string or list of strings (no need for ending newlines if list)
  225. Source code to be written to the file.
  226. ext : optional, string
  227. Extension for the generated file.
  228. Returns
  229. -------
  230. (filename, open filehandle)
  231. It is the caller's responsibility to close the open file and unlink it.
  232. """
  233. fname = tempfile.mkstemp(ext)[1]
  234. f = open(fname,'w')
  235. f.write(src)
  236. f.flush()
  237. return fname, f
  238. def raw_print(*args, **kw):
  239. """Raw print to sys.__stdout__, otherwise identical interface to print()."""
  240. print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
  241. file=sys.__stdout__)
  242. sys.__stdout__.flush()
  243. def raw_print_err(*args, **kw):
  244. """Raw print to sys.__stderr__, otherwise identical interface to print()."""
  245. print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
  246. file=sys.__stderr__)
  247. sys.__stderr__.flush()
  248. # Short aliases for quick debugging, do NOT use these in production code.
  249. rprint = raw_print
  250. rprinte = raw_print_err