##// END OF EJS Templates
io.Term.cin/out/err replaced by io.stdin/out/err...
MinRK -
Show More
@@ -31,8 +31,7 b' import sys'
31
31
32 from IPython.utils import PyColorize
32 from IPython.utils import PyColorize
33 from IPython.core import ipapi
33 from IPython.core import ipapi
34 from IPython.utils import coloransi
34 from IPython.utils import coloransi, io
35 import IPython.utils.io
36 from IPython.core.excolors import exception_colors
35 from IPython.core.excolors import exception_colors
37
36
38 # See if we can use pydb.
37 # See if we can use pydb.
@@ -171,7 +170,7 b' class Pdb(OldPdb):'
171
170
172 # Parent constructor:
171 # Parent constructor:
173 if has_pydb and completekey is None:
172 if has_pydb and completekey is None:
174 OldPdb.__init__(self,stdin=stdin,stdout=IPython.utils.io.Term.cout)
173 OldPdb.__init__(self,stdin=stdin,stdout=io.stdout)
175 else:
174 else:
176 OldPdb.__init__(self,completekey,stdin,stdout)
175 OldPdb.__init__(self,completekey,stdin,stdout)
177
176
@@ -279,7 +278,7 b' class Pdb(OldPdb):'
279 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
278 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
280 context = 3):
279 context = 3):
281 #frame, lineno = frame_lineno
280 #frame, lineno = frame_lineno
282 print >>IPython.utils.io.Term.cout, self.format_stack_entry(frame_lineno, '', context)
281 print >>io.stdout, self.format_stack_entry(frame_lineno, '', context)
283
282
284 # vds: >>
283 # vds: >>
285 frame, lineno = frame_lineno
284 frame, lineno = frame_lineno
@@ -419,7 +418,7 b' class Pdb(OldPdb):'
419 src.append(line)
418 src.append(line)
420 self.lineno = lineno
419 self.lineno = lineno
421
420
422 print >>IPython.utils.io.Term.cout, ''.join(src)
421 print >>io.stdout, ''.join(src)
423
422
424 except KeyboardInterrupt:
423 except KeyboardInterrupt:
425 pass
424 pass
@@ -26,8 +26,7 b' import __builtin__'
26
26
27 from IPython.config.configurable import Configurable
27 from IPython.config.configurable import Configurable
28 from IPython.core import prompts
28 from IPython.core import prompts
29 import IPython.utils.generics
29 from IPython.utils import io
30 import IPython.utils.io
31 from IPython.utils.traitlets import Instance, List
30 from IPython.utils.traitlets import Instance, List
32 from IPython.utils.warn import warn
31 from IPython.utils.warn import warn
33
32
@@ -178,13 +177,13 b' class DisplayHook(Configurable):'
178 """Write the output prompt.
177 """Write the output prompt.
179
178
180 The default implementation simply writes the prompt to
179 The default implementation simply writes the prompt to
181 ``io.Term.cout``.
180 ``io.stdout``.
182 """
181 """
183 # Use write, not print which adds an extra space.
182 # Use write, not print which adds an extra space.
184 IPython.utils.io.Term.cout.write(self.output_sep)
183 io.stdout.write(self.output_sep)
185 outprompt = str(self.prompt_out)
184 outprompt = str(self.prompt_out)
186 if self.do_full_cache:
185 if self.do_full_cache:
187 IPython.utils.io.Term.cout.write(outprompt)
186 io.stdout.write(outprompt)
188
187
189 def compute_format_data(self, result):
188 def compute_format_data(self, result):
190 """Compute format data of the object to be displayed.
189 """Compute format data of the object to be displayed.
@@ -219,7 +218,7 b' class DisplayHook(Configurable):'
219 """Write the format data dict to the frontend.
218 """Write the format data dict to the frontend.
220
219
221 This default version of this method simply writes the plain text
220 This default version of this method simply writes the plain text
222 representation of the object to ``io.Term.cout``. Subclasses should
221 representation of the object to ``io.stdout``. Subclasses should
223 override this method to send the entire `format_dict` to the
222 override this method to send the entire `format_dict` to the
224 frontends.
223 frontends.
225
224
@@ -244,7 +243,7 b' class DisplayHook(Configurable):'
244 # But avoid extraneous empty lines.
243 # But avoid extraneous empty lines.
245 result_repr = '\n' + result_repr
244 result_repr = '\n' + result_repr
246
245
247 print >>IPython.utils.io.Term.cout, result_repr
246 print >>io.stdout, result_repr
248
247
249 def update_user_ns(self, result):
248 def update_user_ns(self, result):
250 """Update user_ns with various things like _, __, _1, etc."""
249 """Update user_ns with various things like _, __, _1, etc."""
@@ -287,8 +286,8 b' class DisplayHook(Configurable):'
287
286
288 def finish_displayhook(self):
287 def finish_displayhook(self):
289 """Finish up all displayhook activities."""
288 """Finish up all displayhook activities."""
290 IPython.utils.io.Term.cout.write(self.output_sep2)
289 io.stdout.write(self.output_sep2)
291 IPython.utils.io.Term.cout.flush()
290 io.stdout.flush()
292
291
293 def __call__(self, result=None):
292 def __call__(self, result=None):
294 """Printing with history cache management.
293 """Printing with history cache management.
@@ -98,9 +98,9 b' class DisplayPublisher(Configurable):'
98 the data.
98 the data.
99 """
99 """
100 from IPython.utils import io
100 from IPython.utils import io
101 # The default is to simply write the plain text data using io.Term.
101 # The default is to simply write the plain text data using io.stdout.
102 if data.has_key('text/plain'):
102 if data.has_key('text/plain'):
103 print(data['text/plain'], file=io.Term.cout)
103 print(data['text/plain'], file=io.stdout)
104
104
105
105
106 def publish_display_data(self, source, data, metadata=None):
106 def publish_display_data(self, source, data, metadata=None):
@@ -22,10 +22,9 b' import threading'
22
22
23 # Our own packages
23 # Our own packages
24 from IPython.config.configurable import Configurable
24 from IPython.config.configurable import Configurable
25 import IPython.utils.io
26
25
27 from IPython.testing import decorators as testdec
26 from IPython.testing import decorators as testdec
28 from IPython.utils.io import ask_yes_no
27 from IPython.utils import io
29 from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode
28 from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode
30 from IPython.utils.warn import warn
29 from IPython.utils.warn import warn
31
30
@@ -630,12 +629,12 b" def magic_history(self, parameter_s = ''):"
630 try:
629 try:
631 outfname = opts['f']
630 outfname = opts['f']
632 except KeyError:
631 except KeyError:
633 outfile = IPython.utils.io.Term.cout # default
632 outfile = io.stdout # default
634 # We don't want to close stdout at the end!
633 # We don't want to close stdout at the end!
635 close_at_end = False
634 close_at_end = False
636 else:
635 else:
637 if os.path.exists(outfname):
636 if os.path.exists(outfname):
638 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
637 if not io.ask_yes_no("File %r exists. Overwrite?" % outfname):
639 print('Aborting.')
638 print('Aborting.')
640 return
639 return
641
640
@@ -45,7 +45,6 b' import os, bisect'
45 import sys
45 import sys
46
46
47 from IPython.core.error import TryNext
47 from IPython.core.error import TryNext
48 import IPython.utils.io
49
48
50 # List here all the default hooks. For now it's just the editor functions
49 # List here all the default hooks. For now it's just the editor functions
51 # but over time we'll move here all the public API for user-accessible things.
50 # but over time we'll move here all the public API for user-accessible things.
@@ -511,14 +511,13 b' class InteractiveShell(Configurable, Magic):'
511 def init_io(self):
511 def init_io(self):
512 # This will just use sys.stdout and sys.stderr. If you want to
512 # This will just use sys.stdout and sys.stderr. If you want to
513 # override sys.stdout and sys.stderr themselves, you need to do that
513 # override sys.stdout and sys.stderr themselves, you need to do that
514 # *before* instantiating this class, because Term holds onto
514 # *before* instantiating this class, because io holds onto
515 # references to the underlying streams.
515 # references to the underlying streams.
516 if sys.platform == 'win32' and self.has_readline:
516 if sys.platform == 'win32' and self.has_readline:
517 Term = io.IOTerm(cout=self.readline._outputfile,
517 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
518 cerr=self.readline._outputfile)
519 else:
518 else:
520 Term = io.IOTerm()
519 io.stdout = io.IOStream(sys.stdout)
521 io.Term = Term
520 io.stderr = io.IOStream(sys.stderr)
522
521
523 def init_prompts(self):
522 def init_prompts(self):
524 # TODO: This is a pass for now because the prompts are managed inside
523 # TODO: This is a pass for now because the prompts are managed inside
@@ -1477,7 +1476,7 b' class InteractiveShell(Configurable, Magic):'
1477 Subclasses may override this method to put the traceback on a different
1476 Subclasses may override this method to put the traceback on a different
1478 place, like a side channel.
1477 place, like a side channel.
1479 """
1478 """
1480 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1479 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1481
1480
1482 def showsyntaxerror(self, filename=None):
1481 def showsyntaxerror(self, filename=None):
1483 """Display the syntax error that just occurred.
1482 """Display the syntax error that just occurred.
@@ -1931,7 +1930,7 b' class InteractiveShell(Configurable, Magic):'
1931 # plain ascii works better w/ pyreadline, on some machines, so
1930 # plain ascii works better w/ pyreadline, on some machines, so
1932 # we use it and only print uncolored rewrite if we have unicode
1931 # we use it and only print uncolored rewrite if we have unicode
1933 rw = str(rw)
1932 rw = str(rw)
1934 print >> IPython.utils.io.Term.cout, rw
1933 print >> io.stdout, rw
1935 except UnicodeEncodeError:
1934 except UnicodeEncodeError:
1936 print "------> " + cmd
1935 print "------> " + cmd
1937
1936
@@ -2325,12 +2324,12 b' class InteractiveShell(Configurable, Magic):'
2325 # TODO: This should be removed when Term is refactored.
2324 # TODO: This should be removed when Term is refactored.
2326 def write(self,data):
2325 def write(self,data):
2327 """Write a string to the default output"""
2326 """Write a string to the default output"""
2328 io.Term.cout.write(data)
2327 io.stdout.write(data)
2329
2328
2330 # TODO: This should be removed when Term is refactored.
2329 # TODO: This should be removed when Term is refactored.
2331 def write_err(self,data):
2330 def write_err(self,data):
2332 """Write a string to the default error output"""
2331 """Write a string to the default error output"""
2333 io.Term.cerr.write(data)
2332 io.stderr.write(data)
2334
2333
2335 def ask_yes_no(self,prompt,default=True):
2334 def ask_yes_no(self,prompt,default=True):
2336 if self.quiet:
2335 if self.quiet:
@@ -10,8 +10,6 b''
10 import re
10 import re
11 import sys
11 import sys
12
12
13 import IPython.utils.io
14
15 coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")
13 coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")
16
14
17 class Macro(object):
15 class Macro(object):
@@ -53,7 +53,6 b' from IPython.lib.pylabtools import mpl_runner'
53 from IPython.external.Itpl import itpl, printpl
53 from IPython.external.Itpl import itpl, printpl
54 from IPython.testing import decorators as testdec
54 from IPython.testing import decorators as testdec
55 from IPython.utils.io import file_read, nlprint
55 from IPython.utils.io import file_read, nlprint
56 import IPython.utils.io
57 from IPython.utils.path import get_py_filename
56 from IPython.utils.path import get_py_filename
58 from IPython.utils.process import arg_split, abbrev_cwd
57 from IPython.utils.process import arg_split, abbrev_cwd
59 from IPython.utils.terminal import set_term_title
58 from IPython.utils.terminal import set_term_title
@@ -31,7 +31,7 b' from itertools import izip_longest'
31 from IPython.core import page
31 from IPython.core import page
32 from IPython.external.Itpl import itpl
32 from IPython.external.Itpl import itpl
33 from IPython.utils import PyColorize
33 from IPython.utils import PyColorize
34 import IPython.utils.io
34 from IPython.utils import io
35 from IPython.utils.text import indent
35 from IPython.utils.text import indent
36 from IPython.utils.wildcard import list_namespace
36 from IPython.utils.wildcard import list_namespace
37 from IPython.utils.coloransi import *
37 from IPython.utils.coloransi import *
@@ -300,7 +300,7 b' class Inspector:'
300 if output is None:
300 if output is None:
301 self.noinfo('definition header',oname)
301 self.noinfo('definition header',oname)
302 else:
302 else:
303 print >>IPython.utils.io.Term.cout, header,self.format(output),
303 print >>io.stdout, header,self.format(output),
304
304
305 def pdoc(self,obj,oname='',formatter = None):
305 def pdoc(self,obj,oname='',formatter = None):
306 """Print the docstring for any object.
306 """Print the docstring for any object.
@@ -36,7 +36,7 b' from IPython.core import ipapi'
36 from IPython.core.error import TryNext
36 from IPython.core.error import TryNext
37 from IPython.utils.cursesimport import use_curses
37 from IPython.utils.cursesimport import use_curses
38 from IPython.utils.data import chop
38 from IPython.utils.data import chop
39 import IPython.utils.io
39 from IPython.utils import io
40 from IPython.utils.process import system
40 from IPython.utils.process import system
41 from IPython.utils.terminal import get_terminal_size
41 from IPython.utils.terminal import get_terminal_size
42
42
@@ -56,18 +56,18 b' def page_dumb(strng, start=0, screen_lines=25):'
56 out_ln = strng.splitlines()[start:]
56 out_ln = strng.splitlines()[start:]
57 screens = chop(out_ln,screen_lines-1)
57 screens = chop(out_ln,screen_lines-1)
58 if len(screens) == 1:
58 if len(screens) == 1:
59 print >>IPython.utils.io.Term.cout, os.linesep.join(screens[0])
59 print >>io.stdout, os.linesep.join(screens[0])
60 else:
60 else:
61 last_escape = ""
61 last_escape = ""
62 for scr in screens[0:-1]:
62 for scr in screens[0:-1]:
63 hunk = os.linesep.join(scr)
63 hunk = os.linesep.join(scr)
64 print >>IPython.utils.io.Term.cout, last_escape + hunk
64 print >>io.stdout, last_escape + hunk
65 if not page_more():
65 if not page_more():
66 return
66 return
67 esc_list = esc_re.findall(hunk)
67 esc_list = esc_re.findall(hunk)
68 if len(esc_list) > 0:
68 if len(esc_list) > 0:
69 last_escape = esc_list[-1]
69 last_escape = esc_list[-1]
70 print >>IPython.utils.io.Term.cout, last_escape + os.linesep.join(screens[-1])
70 print >>io.stdout, last_escape + os.linesep.join(screens[-1])
71
71
72
72
73 def page(strng, start=0, screen_lines=0, pager_cmd=None):
73 def page(strng, start=0, screen_lines=0, pager_cmd=None):
@@ -176,7 +176,7 b' def page(strng, start=0, screen_lines=0, pager_cmd=None):'
176 #print 'numlines',numlines,'screenlines',screen_lines # dbg
176 #print 'numlines',numlines,'screenlines',screen_lines # dbg
177 if numlines <= screen_lines :
177 if numlines <= screen_lines :
178 #print '*** normal print' # dbg
178 #print '*** normal print' # dbg
179 print >>IPython.utils.io.Term.cout, str_toprint
179 print >>io.stdout, str_toprint
180 else:
180 else:
181 # Try to open pager and default to internal one if that fails.
181 # Try to open pager and default to internal one if that fails.
182 # All failure modes are tagged as 'retval=1', to match the return
182 # All failure modes are tagged as 'retval=1', to match the return
@@ -282,13 +282,13 b" if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':"
282
282
283 @return: True if need print more lines, False if quit
283 @return: True if need print more lines, False if quit
284 """
284 """
285 IPython.utils.io.Term.cout.write('---Return to continue, q to quit--- ')
285 io.stdout.write('---Return to continue, q to quit--- ')
286 ans = msvcrt.getch()
286 ans = msvcrt.getch()
287 if ans in ("q", "Q"):
287 if ans in ("q", "Q"):
288 result = False
288 result = False
289 else:
289 else:
290 result = True
290 result = True
291 IPython.utils.io.Term.cout.write("\b"*37 + " "*37 + "\b"*37)
291 io.stdout.write("\b"*37 + " "*37 + "\b"*37)
292 return result
292 return result
293 else:
293 else:
294 def page_more():
294 def page_more():
@@ -37,7 +37,6 b' from IPython.core.splitinput import split_user_input'
37 from IPython.core import page
37 from IPython.core import page
38
38
39 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
39 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
40 import IPython.utils.io
41 from IPython.utils.text import make_quoted_expr
40 from IPython.utils.text import make_quoted_expr
42 from IPython.utils.autoattr import auto_attr
41 from IPython.utils.autoattr import auto_attr
43
42
@@ -325,8 +325,8 b' class TBTools(object):'
325
325
326 # Output stream to write to. Note that we store the original value in
326 # Output stream to write to. Note that we store the original value in
327 # a private attribute and then make the public ostream a property, so
327 # a private attribute and then make the public ostream a property, so
328 # that we can delay accessing io.Term.cout until runtime. The way
328 # that we can delay accessing io.stdout until runtime. The way
329 # things are written now, the Term.cout object is dynamically managed
329 # things are written now, the io.stdout object is dynamically managed
330 # so a reference to it should NEVER be stored statically. This
330 # so a reference to it should NEVER be stored statically. This
331 # property approach confines this detail to a single location, and all
331 # property approach confines this detail to a single location, and all
332 # subclasses can simply access self.ostream for writing.
332 # subclasses can simply access self.ostream for writing.
@@ -349,12 +349,12 b' class TBTools(object):'
349 Valid values are:
349 Valid values are:
350
350
351 - None: the default, which means that IPython will dynamically resolve
351 - None: the default, which means that IPython will dynamically resolve
352 to io.Term.cout. This ensures compatibility with most tools, including
352 to io.stdout. This ensures compatibility with most tools, including
353 Windows (where plain stdout doesn't recognize ANSI escapes).
353 Windows (where plain stdout doesn't recognize ANSI escapes).
354
354
355 - Any object with 'write' and 'flush' attributes.
355 - Any object with 'write' and 'flush' attributes.
356 """
356 """
357 return io.Term.cout if self._ostream is None else self._ostream
357 return io.stdout if self._ostream is None else self._ostream
358
358
359 def _set_ostream(self, val):
359 def _set_ostream(self, val):
360 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
360 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
@@ -176,8 +176,8 b' import shlex'
176 import sys
176 import sys
177
177
178 from IPython.utils.PyColorize import Parser
178 from IPython.utils.PyColorize import Parser
179 from IPython.utils import io
179 from IPython.utils.io import file_read, file_readlines
180 from IPython.utils.io import file_read, file_readlines
180 import IPython.utils.io
181 from IPython.utils.text import marquee
181 from IPython.utils.text import marquee
182
182
183 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
183 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
@@ -319,7 +319,7 b' class Demo(object):'
319
319
320 if index is None:
320 if index is None:
321 if self.finished:
321 if self.finished:
322 print >>IPython.utils.io.Term.cout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.'
322 print >>io.stdout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.'
323 return None
323 return None
324 index = self.block_index
324 index = self.block_index
325 else:
325 else:
@@ -388,9 +388,9 b' class Demo(object):'
388 if index is None:
388 if index is None:
389 return
389 return
390
390
391 print >>IPython.utils.io.Term.cout, self.marquee('<%s> block # %s (%s remaining)' %
391 print >>io.stdout, self.marquee('<%s> block # %s (%s remaining)' %
392 (self.title,index,self.nblocks-index-1))
392 (self.title,index,self.nblocks-index-1))
393 print >>IPython.utils.io.Term.cout,(self.src_blocks_colored[index])
393 print >>io.stdout,(self.src_blocks_colored[index])
394 sys.stdout.flush()
394 sys.stdout.flush()
395
395
396 def show_all(self):
396 def show_all(self):
@@ -403,12 +403,12 b' class Demo(object):'
403 marquee = self.marquee
403 marquee = self.marquee
404 for index,block in enumerate(self.src_blocks_colored):
404 for index,block in enumerate(self.src_blocks_colored):
405 if silent[index]:
405 if silent[index]:
406 print >>IPython.utils.io.Term.cout, marquee('<%s> SILENT block # %s (%s remaining)' %
406 print >>io.stdout, marquee('<%s> SILENT block # %s (%s remaining)' %
407 (title,index,nblocks-index-1))
407 (title,index,nblocks-index-1))
408 else:
408 else:
409 print >>IPython.utils.io.Term.cout, marquee('<%s> block # %s (%s remaining)' %
409 print >>io.stdout, marquee('<%s> block # %s (%s remaining)' %
410 (title,index,nblocks-index-1))
410 (title,index,nblocks-index-1))
411 print >>IPython.utils.io.Term.cout, block,
411 print >>io.stdout, block,
412 sys.stdout.flush()
412 sys.stdout.flush()
413
413
414 def run_cell(self,source):
414 def run_cell(self,source):
@@ -433,18 +433,18 b' class Demo(object):'
433 next_block = self.src_blocks[index]
433 next_block = self.src_blocks[index]
434 self.block_index += 1
434 self.block_index += 1
435 if self._silent[index]:
435 if self._silent[index]:
436 print >>IPython.utils.io.Term.cout, marquee('Executing silent block # %s (%s remaining)' %
436 print >>io.stdout, marquee('Executing silent block # %s (%s remaining)' %
437 (index,self.nblocks-index-1))
437 (index,self.nblocks-index-1))
438 else:
438 else:
439 self.pre_cmd()
439 self.pre_cmd()
440 self.show(index)
440 self.show(index)
441 if self.auto_all or self._auto[index]:
441 if self.auto_all or self._auto[index]:
442 print >>IPython.utils.io.Term.cout, marquee('output:')
442 print >>io.stdout, marquee('output:')
443 else:
443 else:
444 print >>IPython.utils.io.Term.cout, marquee('Press <q> to quit, <Enter> to execute...'),
444 print >>io.stdout, marquee('Press <q> to quit, <Enter> to execute...'),
445 ans = raw_input().strip()
445 ans = raw_input().strip()
446 if ans:
446 if ans:
447 print >>IPython.utils.io.Term.cout, marquee('Block NOT executed')
447 print >>io.stdout, marquee('Block NOT executed')
448 return
448 return
449 try:
449 try:
450 save_argv = sys.argv
450 save_argv = sys.argv
@@ -462,10 +462,10 b' class Demo(object):'
462 if self.block_index == self.nblocks:
462 if self.block_index == self.nblocks:
463 mq1 = self.marquee('END OF DEMO')
463 mq1 = self.marquee('END OF DEMO')
464 if mq1:
464 if mq1:
465 # avoid spurious print >>IPython.utils.io.Term.cout,s if empty marquees are used
465 # avoid spurious print >>io.stdout,s if empty marquees are used
466 print >>IPython.utils.io.Term.cout
466 print >>io.stdout
467 print >>IPython.utils.io.Term.cout, mq1
467 print >>io.stdout, mq1
468 print >>IPython.utils.io.Term.cout, self.marquee('Use <demo_name>.reset() if you want to rerun it.')
468 print >>io.stdout, self.marquee('Use <demo_name>.reset() if you want to rerun it.')
469 self.finished = True
469 self.finished = True
470
470
471 # These methods are meant to be overridden by subclasses who may wish to
471 # These methods are meant to be overridden by subclasses who may wish to
@@ -26,13 +26,21 b' from IPython.external.Itpl import itpl, printpl'
26
26
27 class IOStream:
27 class IOStream:
28
28
29 def __init__(self,stream,fallback):
29 def __init__(self,stream, fallback=None):
30 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
30 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
31 stream = fallback
31 if fallback is not None:
32 stream = fallback
33 else:
34 raise ValueError("fallback required, but not specified")
32 self.stream = stream
35 self.stream = stream
33 self._swrite = stream.write
36 self._swrite = stream.write
34 self.flush = stream.flush
37
35
38 # clone all methods not overridden:
39 def clone(meth):
40 return not hasattr(self, meth) and not meth.startswith('_')
41 for meth in filter(clone, dir(stream)):
42 setattr(self, meth, getattr(stream, meth))
43
36 def write(self,data):
44 def write(self,data):
37 try:
45 try:
38 self._swrite(data)
46 self._swrite(data)
@@ -46,11 +54,21 b' class IOStream:'
46 # if we get here, something is seriously broken.
54 # if we get here, something is seriously broken.
47 print('ERROR - failed to write data to stream:', self.stream,
55 print('ERROR - failed to write data to stream:', self.stream,
48 file=sys.stderr)
56 file=sys.stderr)
57
58 def writelines(self, lines):
59 if isinstance(lines, basestring):
60 lines = [lines]
61 for line in lines:
62 self.write(line)
49
63
50 # This class used to have a writeln method, but regular files and streams
64 # This class used to have a writeln method, but regular files and streams
51 # in Python don't have this method. We need to keep this completely
65 # in Python don't have this method. We need to keep this completely
52 # compatible so we removed it.
66 # compatible so we removed it.
53
67
68 @property
69 def closed(self):
70 return self.stream.closed
71
54 def close(self):
72 def close(self):
55 pass
73 pass
56
74
@@ -65,10 +83,15 b' class IOTerm:'
65 # In the future, having IPython channel all its I/O operations through
83 # 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
84 # 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)
85 # are not a normal terminal (such as a GUI-based shell)
68 def __init__(self, cin=None, cout=None, cerr=None):
86 def __init__(self, stdin=None, stdout=None, stderr=None):
69 self.cin = IOStream(cin, sys.stdin)
87 self.stdin = IOStream(stdin, sys.stdin)
70 self.cout = IOStream(cout, sys.stdout)
88 self.stdout = IOStream(stdout, sys.stdout)
71 self.cerr = IOStream(cerr, sys.stderr)
89 self.stderr = IOStream(stderr, sys.stderr)
90
91 # setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
92 stdin = IOStream(sys.stdin)
93 stdout = IOStream(sys.stdout)
94 stderr = IOStream(sys.stderr)
72
95
73
96
74 class Tee(object):
97 class Tee(object):
@@ -15,6 +15,7 b''
15 import sys
15 import sys
16
16
17 from cStringIO import StringIO
17 from cStringIO import StringIO
18 from subprocess import Popen, PIPE
18
19
19 import nose.tools as nt
20 import nose.tools as nt
20
21
@@ -59,3 +60,12 b' class TeeTestCase(dec.ParametricTestCase):'
59 for chan in ['stdout', 'stderr']:
60 for chan in ['stdout', 'stderr']:
60 for check in ['close', 'del']:
61 for check in ['close', 'del']:
61 yield self.tchan(chan, check)
62 yield self.tchan(chan, check)
63
64 def test_io_init():
65 """Test that io.stdin/out/err exist at startup"""
66 for name in ('stdin', 'stdout', 'stderr'):
67 p = Popen([sys.executable, '-c', "from IPython.utils import io;print io.%s.__class__"%name],
68 stdout=PIPE)
69 p.wait()
70 classname = p.stdout.read().strip()
71 nt.assert_equals(classname, 'IPython.utils.io.IOStream')
@@ -16,7 +16,7 b" Utilities for warnings. Shoudn't we just use the built in warnings module."
16
16
17 import sys
17 import sys
18
18
19 import IPython.utils.io
19 from IPython.utils import io
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Code
22 # Code
@@ -25,7 +25,7 b' import IPython.utils.io'
25 def warn(msg,level=2,exit_val=1):
25 def warn(msg,level=2,exit_val=1):
26 """Standard warning printer. Gives formatting consistency.
26 """Standard warning printer. Gives formatting consistency.
27
27
28 Output is sent to IPython.utils.io.Term.cerr (sys.stderr by default).
28 Output is sent to io.stderr (sys.stderr by default).
29
29
30 Options:
30 Options:
31
31
@@ -41,9 +41,9 b' def warn(msg,level=2,exit_val=1):'
41
41
42 if level>0:
42 if level>0:
43 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
43 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
44 print >> IPython.utils.io.Term.cerr, '%s%s' % (header[level],msg)
44 print >> io.stderr, '%s%s' % (header[level],msg)
45 if level == 4:
45 if level == 4:
46 print >> IPython.utils.io.Term.cerr,'Exiting.\n'
46 print >> io.stderr,'Exiting.\n'
47 sys.exit(exit_val)
47 sys.exit(exit_val)
48
48
49
49
General Comments 0
You need to be logged in to leave comments. Login now