##// END OF EJS Templates
Deprecate io.{stdout,stderr} and shell.{write,write_err}...
Thomas Kluyver -
Show More
@@ -33,7 +33,7 b' import sys'
33
33
34 from IPython import get_ipython
34 from IPython import get_ipython
35 from IPython.utils import PyColorize, ulinecache
35 from IPython.utils import PyColorize, ulinecache
36 from IPython.utils import coloransi, io, py3compat
36 from IPython.utils import coloransi, py3compat
37 from IPython.core.excolors import exception_colors
37 from IPython.core.excolors import exception_colors
38 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.testing.skipdoctest import skip_doctest
39
39
@@ -221,7 +221,7 b' class Pdb(OldPdb):'
221 raise ValueError("Context must be a positive integer")
221 raise ValueError("Context must be a positive integer")
222
222
223 if has_pydb and completekey is None:
223 if has_pydb and completekey is None:
224 OldPdb.__init__(self,stdin=stdin,stdout=io.stdout)
224 OldPdb.__init__(self,stdin=stdin,stdout=sys.stdout)
225 else:
225 else:
226 OldPdb.__init__(self,completekey,stdin,stdout)
226 OldPdb.__init__(self,completekey,stdin,stdout)
227
227
@@ -369,7 +369,7 b' class Pdb(OldPdb):'
369 raise ValueError("Context must be a positive integer")
369 raise ValueError("Context must be a positive integer")
370 except (TypeError, ValueError):
370 except (TypeError, ValueError):
371 raise ValueError("Context must be a positive integer")
371 raise ValueError("Context must be a positive integer")
372 print(self.format_stack_entry(frame_lineno, '', context), file=io.stdout)
372 print(self.format_stack_entry(frame_lineno, '', context))
373
373
374 # vds: >>
374 # vds: >>
375 frame, lineno = frame_lineno
375 frame, lineno = frame_lineno
@@ -513,7 +513,7 b' class Pdb(OldPdb):'
513 src.append(line)
513 src.append(line)
514 self.lineno = lineno
514 self.lineno = lineno
515
515
516 print(''.join(src), file=io.stdout)
516 print(''.join(src))
517
517
518 except KeyboardInterrupt:
518 except KeyboardInterrupt:
519 pass
519 pass
@@ -15,6 +15,7 b' import json'
15 import mimetypes
15 import mimetypes
16 import os
16 import os
17 import struct
17 import struct
18 import sys
18 import warnings
19 import warnings
19
20
20 from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
21 from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
@@ -938,11 +939,10 b' def clear_output(wait=False):'
938 if InteractiveShell.initialized():
939 if InteractiveShell.initialized():
939 InteractiveShell.instance().display_pub.clear_output(wait)
940 InteractiveShell.instance().display_pub.clear_output(wait)
940 else:
941 else:
941 from IPython.utils import io
942 print('\033[2K\r', end='')
942 print('\033[2K\r', file=io.stdout, end='')
943 sys.stdout.flush()
943 io.stdout.flush()
944 print('\033[2K\r', end='')
944 print('\033[2K\r', file=io.stderr, end='')
945 sys.stderr.flush()
945 io.stderr.flush()
946
946
947
947
948 @skip_doctest
948 @skip_doctest
@@ -14,7 +14,6 b' import io as _io'
14 import tokenize
14 import tokenize
15
15
16 from traitlets.config.configurable import Configurable
16 from traitlets.config.configurable import Configurable
17 from IPython.utils import io
18 from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
17 from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
19 from traitlets import Instance, Float
18 from traitlets import Instance, Float
20 from warnings import warn
19 from warnings import warn
@@ -113,10 +112,10 b' class DisplayHook(Configurable):'
113 ``io.stdout``.
112 ``io.stdout``.
114 """
113 """
115 # Use write, not print which adds an extra space.
114 # Use write, not print which adds an extra space.
116 io.stdout.write(self.shell.separate_out)
115 sys.stdout.write(self.shell.separate_out)
117 outprompt = self.shell.prompt_manager.render('out')
116 outprompt = self.shell.prompt_manager.render('out')
118 if self.do_full_cache:
117 if self.do_full_cache:
119 io.stdout.write(outprompt)
118 sys.stdout.write(outprompt)
120
119
121 def compute_format_data(self, result):
120 def compute_format_data(self, result):
122 """Compute format data of the object to be displayed.
121 """Compute format data of the object to be displayed.
@@ -185,7 +184,7 b' class DisplayHook(Configurable):'
185 # But avoid extraneous empty lines.
184 # But avoid extraneous empty lines.
186 result_repr = '\n' + result_repr
185 result_repr = '\n' + result_repr
187
186
188 print(result_repr, file=io.stdout)
187 print(result_repr)
189
188
190 def update_user_ns(self, result):
189 def update_user_ns(self, result):
191 """Update user_ns with various things like _, __, _1, etc."""
190 """Update user_ns with various things like _, __, _1, etc."""
@@ -229,8 +228,8 b' class DisplayHook(Configurable):'
229
228
230 def finish_displayhook(self):
229 def finish_displayhook(self):
231 """Finish up all displayhook activities."""
230 """Finish up all displayhook activities."""
232 io.stdout.write(self.shell.separate_out2)
231 sys.stdout.write(self.shell.separate_out2)
233 io.stdout.flush()
232 sys.stdout.flush()
234
233
235 def __call__(self, result=None):
234 def __call__(self, result=None):
236 """Printing with history cache management.
235 """Printing with history cache management.
@@ -17,8 +17,9 b' spec.'
17
17
18 from __future__ import print_function
18 from __future__ import print_function
19
19
20 import sys
21
20 from traitlets.config.configurable import Configurable
22 from traitlets.config.configurable import Configurable
21 from IPython.utils import io
22 from traitlets import List
23 from traitlets import List
23
24
24 # This used to be defined here - it is imported for backwards compatibility
25 # This used to be defined here - it is imported for backwards compatibility
@@ -92,14 +93,14 b' class DisplayPublisher(Configurable):'
92
93
93 # The default is to simply write the plain text data using io.stdout.
94 # The default is to simply write the plain text data using io.stdout.
94 if 'text/plain' in data:
95 if 'text/plain' in data:
95 print(data['text/plain'], file=io.stdout)
96 print(data['text/plain'])
96
97
97 def clear_output(self, wait=False):
98 def clear_output(self, wait=False):
98 """Clear the output of the cell receiving output."""
99 """Clear the output of the cell receiving output."""
99 print('\033[2K\r', file=io.stdout, end='')
100 print('\033[2K\r', end='')
100 io.stdout.flush()
101 sys.stdout.flush()
101 print('\033[2K\r', file=io.stderr, end='')
102 print('\033[2K\r', end='')
102 io.stderr.flush()
103 sys.stderr.flush()
103
104
104
105
105 class CapturingDisplayPublisher(DisplayPublisher):
106 class CapturingDisplayPublisher(DisplayPublisher):
@@ -1697,11 +1697,11 b' class InteractiveShell(SingletonConfigurable):'
1697 except:
1697 except:
1698 # clear custom handler immediately
1698 # clear custom handler immediately
1699 self.set_custom_exc((), None)
1699 self.set_custom_exc((), None)
1700 print("Custom TB Handler failed, unregistering", file=io.stderr)
1700 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1701 # show the exception in handler first
1701 # show the exception in handler first
1702 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1702 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1703 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1703 print(self.InteractiveTB.stb2text(stb))
1704 print("The original exception:", file=io.stdout)
1704 print("The original exception:")
1705 stb = self.InteractiveTB.structured_traceback(
1705 stb = self.InteractiveTB.structured_traceback(
1706 (etype,value,tb), tb_offset=tb_offset
1706 (etype,value,tb), tb_offset=tb_offset
1707 )
1707 )
@@ -1799,7 +1799,7 b' class InteractiveShell(SingletonConfigurable):'
1799 try:
1799 try:
1800 etype, value, tb = self._get_exc_info(exc_tuple)
1800 etype, value, tb = self._get_exc_info(exc_tuple)
1801 except ValueError:
1801 except ValueError:
1802 self.write_err('No traceback available to show.\n')
1802 print('No traceback available to show.', file=sys.stderr)
1803 return
1803 return
1804
1804
1805 if issubclass(etype, SyntaxError):
1805 if issubclass(etype, SyntaxError):
@@ -1834,7 +1834,7 b' class InteractiveShell(SingletonConfigurable):'
1834 self._showtraceback(etype, value, stb)
1834 self._showtraceback(etype, value, stb)
1835
1835
1836 except KeyboardInterrupt:
1836 except KeyboardInterrupt:
1837 self.write_err('\n' + self.get_exception_only())
1837 print('\n' + self.get_exception_only(), file=sys.stderr)
1838
1838
1839 def _showtraceback(self, etype, evalue, stb):
1839 def _showtraceback(self, etype, evalue, stb):
1840 """Actually show a traceback.
1840 """Actually show a traceback.
@@ -1842,7 +1842,7 b' class InteractiveShell(SingletonConfigurable):'
1842 Subclasses may override this method to put the traceback on a different
1842 Subclasses may override this method to put the traceback on a different
1843 place, like a side channel.
1843 place, like a side channel.
1844 """
1844 """
1845 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1845 print(self.InteractiveTB.stb2text(stb))
1846
1846
1847 def showsyntaxerror(self, filename=None):
1847 def showsyntaxerror(self, filename=None):
1848 """Display the syntax error that just occurred.
1848 """Display the syntax error that just occurred.
@@ -2228,7 +2228,7 b' class InteractiveShell(SingletonConfigurable):'
2228 try:
2228 try:
2229 ec = os.system(cmd)
2229 ec = os.system(cmd)
2230 except KeyboardInterrupt:
2230 except KeyboardInterrupt:
2231 self.write_err('\n' + self.get_exception_only())
2231 print('\n' + self.get_exception_only(), file=sys.stderr)
2232 ec = -2
2232 ec = -2
2233 else:
2233 else:
2234 cmd = py3compat.unicode_to_str(cmd)
2234 cmd = py3compat.unicode_to_str(cmd)
@@ -2247,7 +2247,7 b' class InteractiveShell(SingletonConfigurable):'
2247 ec = subprocess.call(cmd, shell=True, executable=executable)
2247 ec = subprocess.call(cmd, shell=True, executable=executable)
2248 except KeyboardInterrupt:
2248 except KeyboardInterrupt:
2249 # intercept control-C; a long traceback is not useful here
2249 # intercept control-C; a long traceback is not useful here
2250 self.write_err('\n' + self.get_exception_only())
2250 print('\n' + self.get_exception_only(), file=sys.stderr)
2251 ec = 130
2251 ec = 130
2252 if ec > 128:
2252 if ec > 128:
2253 ec = -(ec - 128)
2253 ec = -(ec - 128)
@@ -2351,7 +2351,7 b' class InteractiveShell(SingletonConfigurable):'
2351 # plain ascii works better w/ pyreadline, on some machines, so
2351 # plain ascii works better w/ pyreadline, on some machines, so
2352 # we use it and only print uncolored rewrite if we have unicode
2352 # we use it and only print uncolored rewrite if we have unicode
2353 rw = str(rw)
2353 rw = str(rw)
2354 print(rw, file=io.stdout)
2354 print(rw)
2355 except UnicodeEncodeError:
2355 except UnicodeEncodeError:
2356 print("------> " + cmd)
2356 print("------> " + cmd)
2357
2357
@@ -3056,15 +3056,19 b' class InteractiveShell(SingletonConfigurable):'
3056 tmp_file.close()
3056 tmp_file.close()
3057 return filename
3057 return filename
3058
3058
3059 # TODO: This should be removed when Term is refactored.
3059 @undoc
3060 def write(self,data):
3060 def write(self,data):
3061 """Write a string to the default output"""
3061 """DEPRECATED: Write a string to the default output"""
3062 io.stdout.write(data)
3062 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3063 DeprecationWarning, stacklevel=2)
3064 sys.stdout.write(data)
3063
3065
3064 # TODO: This should be removed when Term is refactored.
3066 @undoc
3065 def write_err(self,data):
3067 def write_err(self,data):
3066 """Write a string to the default error output"""
3068 """DEPRECATED: Write a string to the default error output"""
3067 io.stderr.write(data)
3069 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3070 DeprecationWarning, stacklevel=2)
3071 sys.stderr.write(data)
3068
3072
3069 def ask_yes_no(self, prompt, default=None, interrupt=None):
3073 def ask_yes_no(self, prompt, default=None, interrupt=None):
3070 if self.quiet:
3074 if self.quiet:
@@ -15,6 +15,7 b' from __future__ import print_function'
15
15
16 # Stdlib
16 # Stdlib
17 import os
17 import os
18 import sys
18 from io import open as io_open
19 from io import open as io_open
19
20
20 # Our own packages
21 # Our own packages
@@ -147,7 +148,7 b' class HistoryMagics(Magics):'
147 # Check if output to specific file was requested.
148 # Check if output to specific file was requested.
148 outfname = args.filename
149 outfname = args.filename
149 if not outfname:
150 if not outfname:
150 outfile = io.stdout # default
151 outfile = sys.stdout # default
151 # We don't want to close stdout at the end!
152 # We don't want to close stdout at the end!
152 close_at_end = False
153 close_at_end = False
153 else:
154 else:
@@ -32,7 +32,6 b' from IPython.core import page'
32 from IPython.lib.pretty import pretty
32 from IPython.lib.pretty import pretty
33 from IPython.testing.skipdoctest import skip_doctest_py3
33 from IPython.testing.skipdoctest import skip_doctest_py3
34 from IPython.utils import PyColorize
34 from IPython.utils import PyColorize
35 from IPython.utils import io
36 from IPython.utils import openpy
35 from IPython.utils import openpy
37 from IPython.utils import py3compat
36 from IPython.utils import py3compat
38 from IPython.utils.dir2 import safe_hasattr
37 from IPython.utils.dir2 import safe_hasattr
@@ -427,7 +426,7 b' class Inspector(Colorable):'
427 if output is None:
426 if output is None:
428 self.noinfo('definition header',oname)
427 self.noinfo('definition header',oname)
429 else:
428 else:
430 print(header,self.format(output), end=' ', file=io.stdout)
429 print(header,self.format(output), end=' ')
431
430
432 # In Python 3, all classes are new-style, so they all have __init__.
431 # In Python 3, all classes are new-style, so they all have __init__.
433 @skip_doctest_py3
432 @skip_doctest_py3
@@ -26,7 +26,6 b' from IPython import get_ipython'
26 from IPython.core.display import display
26 from IPython.core.display import display
27 from IPython.core.error import TryNext
27 from IPython.core.error import TryNext
28 from IPython.utils.data import chop
28 from IPython.utils.data import chop
29 from IPython.utils import io
30 from IPython.utils.process import system
29 from IPython.utils.process import system
31 from IPython.utils.terminal import get_terminal_size
30 from IPython.utils.terminal import get_terminal_size
32 from IPython.utils import py3compat
31 from IPython.utils import py3compat
@@ -62,18 +61,18 b' def page_dumb(strng, start=0, screen_lines=25):'
62 out_ln = strng.splitlines()[start:]
61 out_ln = strng.splitlines()[start:]
63 screens = chop(out_ln,screen_lines-1)
62 screens = chop(out_ln,screen_lines-1)
64 if len(screens) == 1:
63 if len(screens) == 1:
65 print(os.linesep.join(screens[0]), file=io.stdout)
64 print(os.linesep.join(screens[0]))
66 else:
65 else:
67 last_escape = ""
66 last_escape = ""
68 for scr in screens[0:-1]:
67 for scr in screens[0:-1]:
69 hunk = os.linesep.join(scr)
68 hunk = os.linesep.join(scr)
70 print(last_escape + hunk, file=io.stdout)
69 print(last_escape + hunk)
71 if not page_more():
70 if not page_more():
72 return
71 return
73 esc_list = esc_re.findall(hunk)
72 esc_list = esc_re.findall(hunk)
74 if len(esc_list) > 0:
73 if len(esc_list) > 0:
75 last_escape = esc_list[-1]
74 last_escape = esc_list[-1]
76 print(last_escape + os.linesep.join(screens[-1]), file=io.stdout)
75 print(last_escape + os.linesep.join(screens[-1]))
77
76
78 def _detect_screen_size(screen_lines_def):
77 def _detect_screen_size(screen_lines_def):
79 """Attempt to work out the number of lines on the screen.
78 """Attempt to work out the number of lines on the screen.
@@ -191,13 +190,13 b' def pager_page(strng, start=0, screen_lines=0, pager_cmd=None):'
191 try:
190 try:
192 screen_lines += _detect_screen_size(screen_lines_def)
191 screen_lines += _detect_screen_size(screen_lines_def)
193 except (TypeError, UnsupportedOperation):
192 except (TypeError, UnsupportedOperation):
194 print(str_toprint, file=io.stdout)
193 print(str_toprint)
195 return
194 return
196
195
197 #print 'numlines',numlines,'screenlines',screen_lines # dbg
196 #print 'numlines',numlines,'screenlines',screen_lines # dbg
198 if numlines <= screen_lines :
197 if numlines <= screen_lines :
199 #print '*** normal print' # dbg
198 #print '*** normal print' # dbg
200 print(str_toprint, file=io.stdout)
199 print(str_toprint)
201 else:
200 else:
202 # Try to open pager and default to internal one if that fails.
201 # Try to open pager and default to internal one if that fails.
203 # All failure modes are tagged as 'retval=1', to match the return
202 # All failure modes are tagged as 'retval=1', to match the return
@@ -339,13 +338,13 b" if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':"
339
338
340 @return: True if need print more lines, False if quit
339 @return: True if need print more lines, False if quit
341 """
340 """
342 io.stdout.write('---Return to continue, q to quit--- ')
341 sys.stdout.write('---Return to continue, q to quit--- ')
343 ans = msvcrt.getwch()
342 ans = msvcrt.getwch()
344 if ans in ("q", "Q"):
343 if ans in ("q", "Q"):
345 result = False
344 result = False
346 else:
345 else:
347 result = True
346 result = True
348 io.stdout.write("\b"*37 + " "*37 + "\b"*37)
347 sys.stdout.write("\b"*37 + " "*37 + "\b"*37)
349 return result
348 return result
350 else:
349 else:
351 def page_more():
350 def page_more():
@@ -196,33 +196,19 b' class InteractiveShellTestCase(unittest.TestCase):'
196
196
197 def test_bad_custom_tb(self):
197 def test_bad_custom_tb(self):
198 """Check that InteractiveShell is protected from bad custom exception handlers"""
198 """Check that InteractiveShell is protected from bad custom exception handlers"""
199 from IPython.utils import io
199 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
200 save_stderr = io.stderr
200 self.assertEqual(ip.custom_exceptions, (IOError,))
201 try:
201 with tt.AssertPrints("Custom TB Handler failed", channel='stderr'):
202 # capture stderr
203 io.stderr = StringIO()
204 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
205 self.assertEqual(ip.custom_exceptions, (IOError,))
206 ip.run_cell(u'raise IOError("foo")')
202 ip.run_cell(u'raise IOError("foo")')
207 self.assertEqual(ip.custom_exceptions, ())
203 self.assertEqual(ip.custom_exceptions, ())
208 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
209 finally:
210 io.stderr = save_stderr
211
204
212 def test_bad_custom_tb_return(self):
205 def test_bad_custom_tb_return(self):
213 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
206 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
214 from IPython.utils import io
207 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
215 save_stderr = io.stderr
208 self.assertEqual(ip.custom_exceptions, (NameError,))
216 try:
209 with tt.AssertPrints("Custom TB Handler failed", channel='stderr'):
217 # capture stderr
218 io.stderr = StringIO()
219 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
220 self.assertEqual(ip.custom_exceptions, (NameError,))
221 ip.run_cell(u'a=abracadabra')
210 ip.run_cell(u'a=abracadabra')
222 self.assertEqual(ip.custom_exceptions, ())
211 self.assertEqual(ip.custom_exceptions, ())
223 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
224 finally:
225 io.stderr = save_stderr
226
212
227 def test_drop_by_id(self):
213 def test_drop_by_id(self):
228 myvars = {"a":object(), "b":object(), "c": object()}
214 myvars = {"a":object(), "b":object(), "c": object()}
@@ -118,7 +118,6 b' from IPython.core import debugger'
118 from IPython.core.display_trap import DisplayTrap
118 from IPython.core.display_trap import DisplayTrap
119 from IPython.core.excolors import exception_colors
119 from IPython.core.excolors import exception_colors
120 from IPython.utils import PyColorize
120 from IPython.utils import PyColorize
121 from IPython.utils import io
122 from IPython.utils import openpy
121 from IPython.utils import openpy
123 from IPython.utils import path as util_path
122 from IPython.utils import path as util_path
124 from IPython.utils import py3compat
123 from IPython.utils import py3compat
@@ -523,7 +522,7 b' class TBTools(colorable.Colorable):'
523
522
524 - Any object with 'write' and 'flush' attributes.
523 - Any object with 'write' and 'flush' attributes.
525 """
524 """
526 return io.stdout if self._ostream is None else self._ostream
525 return sys.stdout if self._ostream is None else self._ostream
527
526
528 def _set_ostream(self, val):
527 def _set_ostream(self, val):
529 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
528 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
@@ -326,7 +326,7 b' class Demo(object):'
326
326
327 if index is None:
327 if index is None:
328 if self.finished:
328 if self.finished:
329 print('Demo finished. Use <demo_name>.reset() if you want to rerun it.', file=io.stdout)
329 print('Demo finished. Use <demo_name>.reset() if you want to rerun it.')
330 return None
330 return None
331 index = self.block_index
331 index = self.block_index
332 else:
332 else:
@@ -397,8 +397,8 b' class Demo(object):'
397 return
397 return
398
398
399 print(self.marquee('<%s> block # %s (%s remaining)' %
399 print(self.marquee('<%s> block # %s (%s remaining)' %
400 (self.title,index,self.nblocks-index-1)), file=io.stdout)
400 (self.title,index,self.nblocks-index-1)))
401 print(self.src_blocks_colored[index], file=io.stdout)
401 print(self.src_blocks_colored[index])
402 sys.stdout.flush()
402 sys.stdout.flush()
403
403
404 def show_all(self):
404 def show_all(self):
@@ -412,11 +412,11 b' class Demo(object):'
412 for index,block in enumerate(self.src_blocks_colored):
412 for index,block in enumerate(self.src_blocks_colored):
413 if silent[index]:
413 if silent[index]:
414 print(marquee('<%s> SILENT block # %s (%s remaining)' %
414 print(marquee('<%s> SILENT block # %s (%s remaining)' %
415 (title,index,nblocks-index-1)), file=io.stdout)
415 (title,index,nblocks-index-1)))
416 else:
416 else:
417 print(marquee('<%s> block # %s (%s remaining)' %
417 print(marquee('<%s> block # %s (%s remaining)' %
418 (title,index,nblocks-index-1)), file=io.stdout)
418 (title,index,nblocks-index-1)))
419 print(block, end=' ', file=io.stdout)
419 print(block, end=' ')
420 sys.stdout.flush()
420 sys.stdout.flush()
421
421
422 def run_cell(self,source):
422 def run_cell(self,source):
@@ -442,17 +442,17 b' class Demo(object):'
442 self.block_index += 1
442 self.block_index += 1
443 if self._silent[index]:
443 if self._silent[index]:
444 print(marquee('Executing silent block # %s (%s remaining)' %
444 print(marquee('Executing silent block # %s (%s remaining)' %
445 (index,self.nblocks-index-1)), file=io.stdout)
445 (index,self.nblocks-index-1)))
446 else:
446 else:
447 self.pre_cmd()
447 self.pre_cmd()
448 self.show(index)
448 self.show(index)
449 if self.auto_all or self._auto[index]:
449 if self.auto_all or self._auto[index]:
450 print(marquee('output:'), file=io.stdout)
450 print(marquee('output:'))
451 else:
451 else:
452 print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ', file=io.stdout)
452 print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ')
453 ans = py3compat.input().strip()
453 ans = py3compat.input().strip()
454 if ans:
454 if ans:
455 print(marquee('Block NOT executed'), file=io.stdout)
455 print(marquee('Block NOT executed'))
456 return
456 return
457 try:
457 try:
458 save_argv = sys.argv
458 save_argv = sys.argv
@@ -471,9 +471,9 b' class Demo(object):'
471 mq1 = self.marquee('END OF DEMO')
471 mq1 = self.marquee('END OF DEMO')
472 if mq1:
472 if mq1:
473 # avoid spurious print >>io.stdout,s if empty marquees are used
473 # avoid spurious print >>io.stdout,s if empty marquees are used
474 print(file=io.stdout)
474 print()
475 print(mq1, file=io.stdout)
475 print(mq1)
476 print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'), file=io.stdout)
476 print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'))
477 self.finished = True
477 self.finished = True
478
478
479 # These methods are meant to be overridden by subclasses who may wish to
479 # These methods are meant to be overridden by subclasses who may wish to
@@ -15,10 +15,12 b' import os'
15 import sys
15 import sys
16 import tempfile
16 import tempfile
17 from warnings import warn
17 from warnings import warn
18
19 from IPython.utils.decorators import undoc
18 from .capture import CapturedIO, capture_output
20 from .capture import CapturedIO, capture_output
19 from .py3compat import string_types, input, PY3
21 from .py3compat import string_types, input, PY3
20
22
21
23 @undoc
22 class IOStream:
24 class IOStream:
23
25
24 def __init__(self,stream, fallback=None):
26 def __init__(self,stream, fallback=None):
@@ -42,6 +44,8 b' class IOStream:'
42 return tpl.format(mod=cls.__module__, cls=cls.__name__, args=self.stream)
44 return tpl.format(mod=cls.__module__, cls=cls.__name__, args=self.stream)
43
45
44 def write(self,data):
46 def write(self,data):
47 warn('IOStream is deprecated, use sys.{stdin,stdout,stderr} instead',
48 DeprecationWarning, stacklevel=2)
45 try:
49 try:
46 self._swrite(data)
50 self._swrite(data)
47 except:
51 except:
@@ -56,6 +60,8 b' class IOStream:'
56 file=sys.stderr)
60 file=sys.stderr)
57
61
58 def writelines(self, lines):
62 def writelines(self, lines):
63 warn('IOStream is deprecated, use sys.{stdin,stdout,stderr} instead',
64 DeprecationWarning, stacklevel=2)
59 if isinstance(lines, string_types):
65 if isinstance(lines, string_types):
60 lines = [lines]
66 lines = [lines]
61 for line in lines:
67 for line in lines:
@@ -9,9 +9,6 b" Utilities for warnings. Shoudn't we just use the built in warnings module."
9 from __future__ import print_function
9 from __future__ import print_function
10
10
11 import sys
11 import sys
12
13 from IPython.utils import io
14
15 import warnings
12 import warnings
16
13
17 warnings.warn("The module IPython.utils.warn is deprecated, use the standard warnings module instead", DeprecationWarning)
14 warnings.warn("The module IPython.utils.warn is deprecated, use the standard warnings module instead", DeprecationWarning)
@@ -36,9 +33,9 b' def warn(msg,level=2,exit_val=1):'
36 warnings.warn("The module IPython.utils.warn is deprecated, use the standard warnings module instead", DeprecationWarning)
33 warnings.warn("The module IPython.utils.warn is deprecated, use the standard warnings module instead", DeprecationWarning)
37 if level>0:
34 if level>0:
38 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
35 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
39 print(header[level], msg, sep='', file=io.stderr)
36 print(header[level], msg, sep='', file=sys.stderr)
40 if level == 4:
37 if level == 4:
41 print('Exiting.\n', file=io.stderr)
38 print('Exiting.\n', file=sys.stderr)
42 sys.exit(exit_val)
39 sys.exit(exit_val)
43
40
44
41
General Comments 0
You need to be logged in to leave comments. Login now