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