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