Navigation Menu

Skip to content

Commit

Permalink
io.Term.cin/out/err replaced by io.stdin/out/err
Browse files Browse the repository at this point in the history
Behavior is now the same as sys.stdin/out/err, and
defaults to those streams.
  • Loading branch information
minrk committed Apr 27, 2011
1 parent 2c9c2c6 commit add1bd1
Show file tree
Hide file tree
Showing 16 changed files with 98 additions and 74 deletions.
9 changes: 4 additions & 5 deletions IPython/core/debugger.py
Expand Up @@ -31,8 +31,7 @@


from IPython.utils import PyColorize from IPython.utils import PyColorize
from IPython.core import ipapi from IPython.core import ipapi
from IPython.utils import coloransi from IPython.utils import coloransi, io
import IPython.utils.io
from IPython.core.excolors import exception_colors from IPython.core.excolors import exception_colors


# See if we can use pydb. # See if we can use pydb.
Expand Down Expand Up @@ -171,7 +170,7 @@ def __init__(self,color_scheme='NoColor',completekey=None,


# Parent constructor: # Parent constructor:
if has_pydb and completekey is None: if has_pydb and completekey is None:
OldPdb.__init__(self,stdin=stdin,stdout=IPython.utils.io.Term.cout) OldPdb.__init__(self,stdin=stdin,stdout=io.stdout)
else: else:
OldPdb.__init__(self,completekey,stdin,stdout) OldPdb.__init__(self,completekey,stdin,stdout)


Expand Down Expand Up @@ -279,7 +278,7 @@ def print_stack_trace(self):
def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
context = 3): context = 3):
#frame, lineno = frame_lineno #frame, lineno = frame_lineno
print >>IPython.utils.io.Term.cout, self.format_stack_entry(frame_lineno, '', context) print >>io.stdout, self.format_stack_entry(frame_lineno, '', context)


# vds: >> # vds: >>
frame, lineno = frame_lineno frame, lineno = frame_lineno
Expand Down Expand Up @@ -419,7 +418,7 @@ def print_list_lines(self, filename, first, last):
src.append(line) src.append(line)
self.lineno = lineno self.lineno = lineno


print >>IPython.utils.io.Term.cout, ''.join(src) print >>io.stdout, ''.join(src)


except KeyboardInterrupt: except KeyboardInterrupt:
pass pass
Expand Down
17 changes: 8 additions & 9 deletions IPython/core/displayhook.py
Expand Up @@ -26,8 +26,7 @@


from IPython.config.configurable import Configurable from IPython.config.configurable import Configurable
from IPython.core import prompts from IPython.core import prompts
import IPython.utils.generics from IPython.utils import io
import IPython.utils.io
from IPython.utils.traitlets import Instance, List from IPython.utils.traitlets import Instance, List
from IPython.utils.warn import warn from IPython.utils.warn import warn


Expand Down Expand Up @@ -178,13 +177,13 @@ def write_output_prompt(self):
"""Write the output prompt. """Write the output prompt.
The default implementation simply writes the prompt to The default implementation simply writes the prompt to
``io.Term.cout``. ``io.stdout``.
""" """
# Use write, not print which adds an extra space. # Use write, not print which adds an extra space.
IPython.utils.io.Term.cout.write(self.output_sep) io.stdout.write(self.output_sep)
outprompt = str(self.prompt_out) outprompt = str(self.prompt_out)
if self.do_full_cache: if self.do_full_cache:
IPython.utils.io.Term.cout.write(outprompt) io.stdout.write(outprompt)


def compute_format_data(self, result): def compute_format_data(self, result):
"""Compute format data of the object to be displayed. """Compute format data of the object to be displayed.
Expand Down Expand Up @@ -219,7 +218,7 @@ def write_format_data(self, format_dict):
"""Write the format data dict to the frontend. """Write the format data dict to the frontend.
This default version of this method simply writes the plain text This default version of this method simply writes the plain text
representation of the object to ``io.Term.cout``. Subclasses should representation of the object to ``io.stdout``. Subclasses should
override this method to send the entire `format_dict` to the override this method to send the entire `format_dict` to the
frontends. frontends.
Expand All @@ -244,7 +243,7 @@ def write_format_data(self, format_dict):
# But avoid extraneous empty lines. # But avoid extraneous empty lines.
result_repr = '\n' + result_repr result_repr = '\n' + result_repr


print >>IPython.utils.io.Term.cout, result_repr print >>io.stdout, result_repr


def update_user_ns(self, result): def update_user_ns(self, result):
"""Update user_ns with various things like _, __, _1, etc.""" """Update user_ns with various things like _, __, _1, etc."""
Expand Down Expand Up @@ -287,8 +286,8 @@ def log_output(self, format_dict):


def finish_displayhook(self): def finish_displayhook(self):
"""Finish up all displayhook activities.""" """Finish up all displayhook activities."""
IPython.utils.io.Term.cout.write(self.output_sep2) io.stdout.write(self.output_sep2)
IPython.utils.io.Term.cout.flush() io.stdout.flush()


def __call__(self, result=None): def __call__(self, result=None):
"""Printing with history cache management. """Printing with history cache management.
Expand Down
4 changes: 2 additions & 2 deletions IPython/core/displaypub.py
Expand Up @@ -98,9 +98,9 @@ def publish(self, source, data, metadata=None):
the data. the data.
""" """
from IPython.utils import io from IPython.utils import io
# The default is to simply write the plain text data using io.Term. # The default is to simply write the plain text data using io.stdout.
if data.has_key('text/plain'): if data.has_key('text/plain'):
print(data['text/plain'], file=io.Term.cout) print(data['text/plain'], file=io.stdout)




def publish_display_data(self, source, data, metadata=None): def publish_display_data(self, source, data, metadata=None):
Expand Down
7 changes: 3 additions & 4 deletions IPython/core/history.py
Expand Up @@ -22,10 +22,9 @@


# Our own packages # Our own packages
from IPython.config.configurable import Configurable from IPython.config.configurable import Configurable
import IPython.utils.io


from IPython.testing import decorators as testdec from IPython.testing import decorators as testdec
from IPython.utils.io import ask_yes_no from IPython.utils import io
from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode
from IPython.utils.warn import warn from IPython.utils.warn import warn


Expand Down Expand Up @@ -630,12 +629,12 @@ def _format_lineno(session, line):
try: try:
outfname = opts['f'] outfname = opts['f']
except KeyError: except KeyError:
outfile = IPython.utils.io.Term.cout # default outfile = io.stdout # default
# We don't want to close stdout at the end! # We don't want to close stdout at the end!
close_at_end = False close_at_end = False
else: else:
if os.path.exists(outfname): if os.path.exists(outfname):
if not ask_yes_no("File %r exists. Overwrite?" % outfname): if not io.ask_yes_no("File %r exists. Overwrite?" % outfname):
print('Aborting.') print('Aborting.')
return return


Expand Down
1 change: 0 additions & 1 deletion IPython/core/hooks.py
Expand Up @@ -45,7 +45,6 @@ def calljed(self,filename, linenum):
import sys import sys


from IPython.core.error import TryNext from IPython.core.error import TryNext
import IPython.utils.io


# List here all the default hooks. For now it's just the editor functions # List here all the default hooks. For now it's just the editor functions
# but over time we'll move here all the public API for user-accessible things. # but over time we'll move here all the public API for user-accessible things.
Expand Down
17 changes: 8 additions & 9 deletions IPython/core/interactiveshell.py
Expand Up @@ -511,14 +511,13 @@ def init_inspector(self):
def init_io(self): def init_io(self):
# This will just use sys.stdout and sys.stderr. If you want to # This will just use sys.stdout and sys.stderr. If you want to
# override sys.stdout and sys.stderr themselves, you need to do that # override sys.stdout and sys.stderr themselves, you need to do that
# *before* instantiating this class, because Term holds onto # *before* instantiating this class, because io holds onto
# references to the underlying streams. # references to the underlying streams.
if sys.platform == 'win32' and self.has_readline: if sys.platform == 'win32' and self.has_readline:
Term = io.IOTerm(cout=self.readline._outputfile, io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
cerr=self.readline._outputfile)
else: else:
Term = io.IOTerm() io.stdout = io.IOStream(sys.stdout)
io.Term = Term io.stderr = io.IOStream(sys.stderr)


def init_prompts(self): def init_prompts(self):
# TODO: This is a pass for now because the prompts are managed inside # TODO: This is a pass for now because the prompts are managed inside
Expand Down Expand Up @@ -1477,7 +1476,7 @@ def _showtraceback(self, etype, evalue, stb):
Subclasses may override this method to put the traceback on a different Subclasses may override this method to put the traceback on a different
place, like a side channel. place, like a side channel.
""" """
print >> io.Term.cout, self.InteractiveTB.stb2text(stb) print >> io.stdout, self.InteractiveTB.stb2text(stb)


def showsyntaxerror(self, filename=None): def showsyntaxerror(self, filename=None):
"""Display the syntax error that just occurred. """Display the syntax error that just occurred.
Expand Down Expand Up @@ -1931,7 +1930,7 @@ def auto_rewrite_input(self, cmd):
# plain ascii works better w/ pyreadline, on some machines, so # plain ascii works better w/ pyreadline, on some machines, so
# we use it and only print uncolored rewrite if we have unicode # we use it and only print uncolored rewrite if we have unicode
rw = str(rw) rw = str(rw)
print >> IPython.utils.io.Term.cout, rw print >> io.stdout, rw
except UnicodeEncodeError: except UnicodeEncodeError:
print "------> " + cmd print "------> " + cmd


Expand Down Expand Up @@ -2325,12 +2324,12 @@ def mktempfile(self, data=None, prefix='ipython_edit_'):
# TODO: This should be removed when Term is refactored. # TODO: This should be removed when Term is refactored.
def write(self,data): def write(self,data):
"""Write a string to the default output""" """Write a string to the default output"""
io.Term.cout.write(data) io.stdout.write(data)


# TODO: This should be removed when Term is refactored. # TODO: This should be removed when Term is refactored.
def write_err(self,data): def write_err(self,data):
"""Write a string to the default error output""" """Write a string to the default error output"""
io.Term.cerr.write(data) io.stderr.write(data)


def ask_yes_no(self,prompt,default=True): def ask_yes_no(self,prompt,default=True):
if self.quiet: if self.quiet:
Expand Down
2 changes: 0 additions & 2 deletions IPython/core/macro.py
Expand Up @@ -10,8 +10,6 @@
import re import re
import sys import sys


import IPython.utils.io

coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)") coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")


class Macro(object): class Macro(object):
Expand Down
1 change: 0 additions & 1 deletion IPython/core/magic.py
Expand Up @@ -53,7 +53,6 @@
from IPython.external.Itpl import itpl, printpl from IPython.external.Itpl import itpl, printpl
from IPython.testing import decorators as testdec from IPython.testing import decorators as testdec
from IPython.utils.io import file_read, nlprint from IPython.utils.io import file_read, nlprint
import IPython.utils.io
from IPython.utils.path import get_py_filename from IPython.utils.path import get_py_filename
from IPython.utils.process import arg_split, abbrev_cwd from IPython.utils.process import arg_split, abbrev_cwd
from IPython.utils.terminal import set_term_title from IPython.utils.terminal import set_term_title
Expand Down
4 changes: 2 additions & 2 deletions IPython/core/oinspect.py
Expand Up @@ -31,7 +31,7 @@
from IPython.core import page from IPython.core import page
from IPython.external.Itpl import itpl from IPython.external.Itpl import itpl
from IPython.utils import PyColorize from IPython.utils import PyColorize
import IPython.utils.io from IPython.utils import io
from IPython.utils.text import indent from IPython.utils.text import indent
from IPython.utils.wildcard import list_namespace from IPython.utils.wildcard import list_namespace
from IPython.utils.coloransi import * from IPython.utils.coloransi import *
Expand Down Expand Up @@ -300,7 +300,7 @@ def pdef(self,obj,oname=''):
if output is None: if output is None:
self.noinfo('definition header',oname) self.noinfo('definition header',oname)
else: else:
print >>IPython.utils.io.Term.cout, header,self.format(output), print >>io.stdout, header,self.format(output),


def pdoc(self,obj,oname='',formatter = None): def pdoc(self,obj,oname='',formatter = None):
"""Print the docstring for any object. """Print the docstring for any object.
Expand Down
14 changes: 7 additions & 7 deletions IPython/core/page.py
Expand Up @@ -36,7 +36,7 @@
from IPython.core.error import TryNext from IPython.core.error import TryNext
from IPython.utils.cursesimport import use_curses from IPython.utils.cursesimport import use_curses
from IPython.utils.data import chop from IPython.utils.data import chop
import IPython.utils.io from IPython.utils import io
from IPython.utils.process import system from IPython.utils.process import system
from IPython.utils.terminal import get_terminal_size from IPython.utils.terminal import get_terminal_size


Expand All @@ -56,18 +56,18 @@ def page_dumb(strng, start=0, screen_lines=25):
out_ln = strng.splitlines()[start:] out_ln = strng.splitlines()[start:]
screens = chop(out_ln,screen_lines-1) screens = chop(out_ln,screen_lines-1)
if len(screens) == 1: if len(screens) == 1:
print >>IPython.utils.io.Term.cout, os.linesep.join(screens[0]) print >>io.stdout, os.linesep.join(screens[0])
else: else:
last_escape = "" last_escape = ""
for scr in screens[0:-1]: for scr in screens[0:-1]:
hunk = os.linesep.join(scr) hunk = os.linesep.join(scr)
print >>IPython.utils.io.Term.cout, last_escape + hunk print >>io.stdout, last_escape + hunk
if not page_more(): if not page_more():
return return
esc_list = esc_re.findall(hunk) esc_list = esc_re.findall(hunk)
if len(esc_list) > 0: if len(esc_list) > 0:
last_escape = esc_list[-1] last_escape = esc_list[-1]
print >>IPython.utils.io.Term.cout, last_escape + os.linesep.join(screens[-1]) print >>io.stdout, last_escape + os.linesep.join(screens[-1])




def page(strng, start=0, screen_lines=0, pager_cmd=None): def page(strng, start=0, screen_lines=0, pager_cmd=None):
Expand Down Expand Up @@ -176,7 +176,7 @@ def page(strng, start=0, screen_lines=0, pager_cmd=None):
#print 'numlines',numlines,'screenlines',screen_lines # dbg #print 'numlines',numlines,'screenlines',screen_lines # dbg
if numlines <= screen_lines : if numlines <= screen_lines :
#print '*** normal print' # dbg #print '*** normal print' # dbg
print >>IPython.utils.io.Term.cout, str_toprint print >>io.stdout, str_toprint
else: else:
# Try to open pager and default to internal one if that fails. # Try to open pager and default to internal one if that fails.
# All failure modes are tagged as 'retval=1', to match the return # All failure modes are tagged as 'retval=1', to match the return
Expand Down Expand Up @@ -282,13 +282,13 @@ def page_more():
@return: True if need print more lines, False if quit @return: True if need print more lines, False if quit
""" """
IPython.utils.io.Term.cout.write('---Return to continue, q to quit--- ') io.stdout.write('---Return to continue, q to quit--- ')
ans = msvcrt.getch() ans = msvcrt.getch()
if ans in ("q", "Q"): if ans in ("q", "Q"):
result = False result = False
else: else:
result = True result = True
IPython.utils.io.Term.cout.write("\b"*37 + " "*37 + "\b"*37) io.stdout.write("\b"*37 + " "*37 + "\b"*37)
return result return result
else: else:
def page_more(): def page_more():
Expand Down
1 change: 0 additions & 1 deletion IPython/core/prefilter.py
Expand Up @@ -37,7 +37,6 @@
from IPython.core import page from IPython.core import page


from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
import IPython.utils.io
from IPython.utils.text import make_quoted_expr from IPython.utils.text import make_quoted_expr
from IPython.utils.autoattr import auto_attr from IPython.utils.autoattr import auto_attr


Expand Down
8 changes: 4 additions & 4 deletions IPython/core/ultratb.py
Expand Up @@ -325,8 +325,8 @@ def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):


# Output stream to write to. Note that we store the original value in # Output stream to write to. Note that we store the original value in
# a private attribute and then make the public ostream a property, so # a private attribute and then make the public ostream a property, so
# that we can delay accessing io.Term.cout until runtime. The way # that we can delay accessing io.stdout until runtime. The way
# things are written now, the Term.cout object is dynamically managed # things are written now, the io.stdout object is dynamically managed
# so a reference to it should NEVER be stored statically. This # so a reference to it should NEVER be stored statically. This
# property approach confines this detail to a single location, and all # property approach confines this detail to a single location, and all
# subclasses can simply access self.ostream for writing. # subclasses can simply access self.ostream for writing.
Expand All @@ -349,12 +349,12 @@ def _get_ostream(self):
Valid values are: Valid values are:
- None: the default, which means that IPython will dynamically resolve - None: the default, which means that IPython will dynamically resolve
to io.Term.cout. This ensures compatibility with most tools, including to io.stdout. This ensures compatibility with most tools, including
Windows (where plain stdout doesn't recognize ANSI escapes). Windows (where plain stdout doesn't recognize ANSI escapes).
- Any object with 'write' and 'flush' attributes. - Any object with 'write' and 'flush' attributes.
""" """
return io.Term.cout if self._ostream is None else self._ostream return io.stdout if self._ostream is None else self._ostream


def _set_ostream(self, val): def _set_ostream(self, val):
assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
Expand Down

0 comments on commit add1bd1

Please sign in to comment.