From 0369b784fd8a562fefe21467507a2a53ed91313e 2012-07-13 08:07:56 From: Bussonnier Matthias Date: 2012-07-13 08:07:56 Subject: [PATCH] Merge pull request #2100 from Carreau/2to3fixes python 2 and 3 compatibility without 2to3 apply some fixes : - apply (deactivated in setup.py now) - repr (deactivated in setup.py now) - print (only in modules with print >>) - raise (partially) don't touch deathrow and quarantine. --- diff --git a/IPython/core/crashhandler.py b/IPython/core/crashhandler.py index 39e5ae2..1d405cf 100644 --- a/IPython/core/crashhandler.py +++ b/IPython/core/crashhandler.py @@ -18,6 +18,7 @@ Authors: #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- +from __future__ import print_function import os import sys @@ -159,18 +160,18 @@ class CrashHandler(object): # print traceback to screen if self.show_crash_traceback: - print >> sys.stderr, traceback + print(traceback, file=sys.stderr) # and generate a complete report on disk try: report = open(report_name,'w') except: - print >> sys.stderr, 'Could not create crash report on disk.' + print('Could not create crash report on disk.', file=sys.stderr) return # Inform user on stderr of what happened - print >> sys.stderr, '\n'+'*'*70+'\n' - print >> sys.stderr, self.message_template.format(**self.info) + print('\n'+'*'*70+'\n', file=sys.stderr) + print(self.message_template.format(**self.info), file=sys.stderr) # Construct report on disk report.write(self.make_report(traceback)) @@ -210,5 +211,5 @@ def crash_handler_lite(etype, evalue, tb): else: # we are not in a shell, show generic config config = "c." - print >> sys.stderr, _lite_message_template.format(email=author_email, config=config) + print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr) diff --git a/IPython/core/debugger.py b/IPython/core/debugger.py index e175fc4..6af9c6f 100644 --- a/IPython/core/debugger.py +++ b/IPython/core/debugger.py @@ -24,6 +24,7 @@ http://www.python.org/2.2.3/license.html""" # # #***************************************************************************** +from __future__ import print_function import bdb import linecache @@ -46,7 +47,7 @@ if '--pydb' in sys.argv: # better protect against it. has_pydb = True except ImportError: - print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available" + print("Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available") if has_pydb: from pydb import Pdb as OldPdb @@ -60,12 +61,12 @@ else: # the Tracer constructor. def BdbQuit_excepthook(et,ev,tb): if et==bdb.BdbQuit: - print 'Exiting Debugger.' + print('Exiting Debugger.') else: BdbQuit_excepthook.excepthook_ori(et,ev,tb) def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None): - print 'Exiting Debugger.' + print('Exiting Debugger.') class Tracer(object): @@ -294,7 +295,7 @@ class Pdb(OldPdb): def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', context = 3): #frame, lineno = frame_lineno - print >>io.stdout, self.format_stack_entry(frame_lineno, '', context) + print(self.format_stack_entry(frame_lineno, '', context), file=io.stdout) # vds: >> frame, lineno = frame_lineno @@ -434,7 +435,7 @@ class Pdb(OldPdb): src.append(line) self.lineno = lineno - print >>io.stdout, ''.join(src) + print(''.join(src), file=io.stdout) except KeyboardInterrupt: pass @@ -455,7 +456,7 @@ class Pdb(OldPdb): else: first = max(1, int(x) - 5) except: - print '*** Error in argument:', `arg` + print('*** Error in argument:', repr(arg)) return elif self.lineno is None: first = max(1, self.curframe.f_lineno - 5) @@ -514,12 +515,12 @@ class Pdb(OldPdb): ####################################################################### if not line: - print >>self.stdout, 'End of file' + print('End of file', file=self.stdout) return 0 line = line.strip() # Don't allow setting breakpoint at a blank line if (not line or (line[0] == '#') or (line[:3] == '"""') or line[:3] == "'''"): - print >>self.stdout, '*** Blank or comment' + print('*** Blank or comment', file=self.stdout) return 0 return lineno diff --git a/IPython/core/displayhook.py b/IPython/core/displayhook.py index 5eebb5f..9890b3d 100644 --- a/IPython/core/displayhook.py +++ b/IPython/core/displayhook.py @@ -21,6 +21,7 @@ Authors: #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- +from __future__ import print_function import __builtin__ @@ -179,7 +180,7 @@ class DisplayHook(Configurable): # But avoid extraneous empty lines. result_repr = '\n' + result_repr - print >>io.stdout, result_repr + print(result_repr, file=io.stdout) def update_user_ns(self, result): """Update user_ns with various things like _, __, _1, etc.""" @@ -188,7 +189,7 @@ class DisplayHook(Configurable): if result is not self.shell.user_ns['_oh']: if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: warn('Output cache limit (currently '+ - `self.cache_size`+' entries) hit.\n' + repr(self.cache_size)+' entries) hit.\n' 'Flushing cache and resetting history counter...\n' 'The only history variables available will be _,__,___ and _1\n' 'with the current result.') @@ -208,7 +209,7 @@ class DisplayHook(Configurable): # hackish access to top-level namespace to create _1,_2... dynamically to_main = {} if self.do_full_cache: - new_result = '_'+`self.prompt_count` + new_result = '_'+repr(self.prompt_count) to_main[new_result] = result self.shell.push(to_main, interactive=False) self.shell.user_ns['_oh'][self.prompt_count] = result @@ -243,12 +244,12 @@ class DisplayHook(Configurable): def flush(self): if not self.do_full_cache: - raise ValueError,"You shouldn't have reached the cache flush "\ - "if full caching is not enabled!" + raise ValueError("You shouldn't have reached the cache flush " + "if full caching is not enabled!") # delete auto-generated vars from global namespace for n in range(1,self.prompt_count + 1): - key = '_'+`n` + key = '_'+repr(n) try: del self.shell.user_ns[key] except: pass diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py index 03b9c9b..3aa526a 100644 --- a/IPython/core/interactiveshell.py +++ b/IPython/core/interactiveshell.py @@ -16,6 +16,7 @@ from __future__ import with_statement from __future__ import absolute_import +from __future__ import print_function import __builtin__ as builtin_mod import __future__ @@ -792,8 +793,8 @@ class InteractiveShell(SingletonConfigurable): dp = getattr(self.hooks, name, None) if name not in IPython.core.hooks.__all__: - print "Warning! Hook '%s' is not one of %s" % \ - (name, IPython.core.hooks.__all__ ) + print("Warning! Hook '%s' is not one of %s" % \ + (name, IPython.core.hooks.__all__ )) if not dp: dp = IPython.core.hooks.CommandChainDispatcher() @@ -901,7 +902,7 @@ class InteractiveShell(SingletonConfigurable): def _set_call_pdb(self,val): if val not in (0,1,False,True): - raise ValueError,'new call_pdb value must be boolean' + raise ValueError('new call_pdb value must be boolean') # store value in instance self._call_pdb = val @@ -1314,7 +1315,7 @@ class InteractiveShell(SingletonConfigurable): try: vdict[name] = eval(name, cf.f_globals, cf.f_locals) except: - print ('Could not get variable %s from %s' % + print('Could not get variable %s from %s' % (name,cf.f_code.co_name)) else: raise ValueError('variables must be a dict/str/list/tuple') @@ -1489,7 +1490,7 @@ class InteractiveShell(SingletonConfigurable): else: pmethod(info.obj, oname) else: - print 'Object `%s` not found.' % oname + print('Object `%s` not found.' % oname) return 'not found' # so callers can take other action def object_inspect(self, oname, detail_level=0): @@ -1583,10 +1584,10 @@ class InteractiveShell(SingletonConfigurable): "The custom exceptions must be given AS A TUPLE." def dummy_handler(self,etype,value,tb,tb_offset=None): - print '*** Simple custom exception handler ***' - print 'Exception type :',etype - print 'Exception value:',value - print 'Traceback :',tb + print('*** Simple custom exception handler ***') + print('Exception type :',etype) + print('Exception value:',value) + print('Traceback :',tb) #print 'Source code :','\n'.join(self.buffer) def validate_stb(stb): @@ -1627,11 +1628,11 @@ class InteractiveShell(SingletonConfigurable): except: # clear custom handler immediately self.set_custom_exc((), None) - print >> io.stderr, "Custom TB Handler failed, unregistering" + print("Custom TB Handler failed, unregistering", file=io.stderr) # show the exception in handler first stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) - print >> io.stdout, self.InteractiveTB.stb2text(stb) - print >> io.stdout, "The original exception:" + print(self.InteractiveTB.stb2text(stb), file=io.stdout) + print("The original exception:", file=io.stdout) stb = self.InteractiveTB.structured_traceback( (etype,value,tb), tb_offset=tb_offset ) @@ -1755,7 +1756,7 @@ class InteractiveShell(SingletonConfigurable): Subclasses may override this method to put the traceback on a different place, like a side channel. """ - print >> io.stdout, self.InteractiveTB.stb2text(stb) + print(self.InteractiveTB.stb2text(stb), file=io.stdout) def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred. @@ -2331,9 +2332,9 @@ class InteractiveShell(SingletonConfigurable): # plain ascii works better w/ pyreadline, on some machines, so # we use it and only print uncolored rewrite if we have unicode rw = str(rw) - print >> io.stdout, rw + print(rw, file=io.stdout) except UnicodeEncodeError: - print "------> " + cmd + print("------> " + cmd) #------------------------------------------------------------------------- # Things related to extracting values/expressions from kernel and user_ns @@ -2622,17 +2623,17 @@ class InteractiveShell(SingletonConfigurable): try: func() except KeyboardInterrupt: - print >> io.stderr, "\nKeyboardInterrupt" + print("\nKeyboardInterrupt", file=io.stderr) except Exception: # register as failing: self._post_execute[func] = False self.showtraceback() - print >> io.stderr, '\n'.join([ + print('\n'.join([ "post-execution function %r produced an error." % func, "If this problem persists, you can disable failing post-exec functions with:", "", " get_ipython().disable_failing_post_execute = True" - ]) + ]), file=io.stderr) if store_history: # Write output to the database. Does nothing unless @@ -2694,7 +2695,7 @@ class InteractiveShell(SingletonConfigurable): # Flush softspace if softspace(sys.stdout, 0): - print + print() except: # It's possible to have exceptions raised here, typically by diff --git a/IPython/core/logger.py b/IPython/core/logger.py index 56bc4d2..d6eff7a 100644 --- a/IPython/core/logger.py +++ b/IPython/core/logger.py @@ -54,7 +54,7 @@ class Logger(object): # logmode is a validated property def _set_mode(self,mode): if mode not in ['append','backup','global','over','rotate']: - raise ValueError,'invalid log mode %s given' % mode + raise ValueError('invalid log mode %s given' % mode) self._logmode = mode def _get_mode(self): @@ -117,7 +117,7 @@ class Logger(object): for f in old: root, ext = os.path.splitext(f) num = int(ext[1:-1])+1 - os.rename(f, root+'.'+`num`.zfill(3)+'~') + os.rename(f, root+'.'+repr(num).zfill(3)+'~') os.rename(self.logfname, self.logfname+'.001~') self.logfile = io.open(self.logfname, 'w', encoding='utf-8') @@ -131,8 +131,8 @@ class Logger(object): """Switch logging on/off. val should be ONLY a boolean.""" if val not in [False,True,0,1]: - raise ValueError, \ - 'Call switch_log ONLY with a boolean argument, not with:',val + raise ValueError('Call switch_log ONLY with a boolean argument, ' + 'not with: %s' % val) label = {0:'OFF',1:'ON',False:'OFF',True:'ON'} diff --git a/IPython/core/magic.py b/IPython/core/magic.py index db52820..1be6d12 100644 --- a/IPython/core/magic.py +++ b/IPython/core/magic.py @@ -568,7 +568,7 @@ class Magics(object): mode = kw.get('mode','string') if mode not in ['string','list']: - raise ValueError,'incorrect mode given: %s' % mode + raise ValueError('incorrect mode given: %s' % mode) # Get options list_all = kw.get('list_all',0) posix = kw.get('posix', os.name == 'posix') diff --git a/IPython/core/magics/execution.py b/IPython/core/magics/execution.py index e111873..d89f17f 100644 --- a/IPython/core/magics/execution.py +++ b/IPython/core/magics/execution.py @@ -254,14 +254,14 @@ python-profiler package from non-free.""") dump_file = unquote_filename(dump_file) prof.dump_stats(dump_file) print '\n*** Profile stats marshalled to file',\ - `dump_file`+'.',sys_exit + repr(dump_file)+'.',sys_exit if text_file: text_file = unquote_filename(text_file) pfile = open(text_file,'w') pfile.write(output) pfile.close() print '\n*** Profile printout saved to text file',\ - `text_file`+'.',sys_exit + repr(text_file)+'.',sys_exit if opts.has_key('r'): return stats diff --git a/IPython/core/oinspect.py b/IPython/core/oinspect.py index 3a0530c..4c9a8fb 100644 --- a/IPython/core/oinspect.py +++ b/IPython/core/oinspect.py @@ -13,6 +13,7 @@ reference the name under which an object is being read. # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #***************************************************************************** +from __future__ import print_function __all__ = ['Inspector','InspectColors'] @@ -335,11 +336,11 @@ class Inspector: def noinfo(self, msg, oname): """Generic message when no information is found.""" - print 'No %s found' % msg, + print('No %s found' % msg, end=' ') if oname: - print 'for %s' % oname + print('for %s' % oname) else: - print + print() def pdef(self, obj, oname=''): """Print the definition header for any callable object. @@ -347,7 +348,7 @@ class Inspector: If the object is a class, print the constructor information.""" if not callable(obj): - print 'Object is not callable.' + print('Object is not callable.') return header = '' @@ -362,7 +363,7 @@ class Inspector: if output is None: self.noinfo('definition header',oname) else: - print >>io.stdout, header,self.format(output), + print(header,self.format(output), end=' ', file=io.stdout) # In Python 3, all classes are new-style, so they all have __init__. @skip_doctest_py3 @@ -449,9 +450,9 @@ class Inspector: # is defined, as long as the file isn't binary and is actually on the # filesystem. if ofile.endswith(('.so', '.dll', '.pyd')): - print 'File %r is binary, not printing.' % ofile + print('File %r is binary, not printing.' % ofile) elif not os.path.isfile(ofile): - print 'File %r does not exist, not printing.' % ofile + print('File %r does not exist, not printing.' % ofile) else: # Print only text files, not extension binaries. Note that # getsourcelines returns lineno with 1-offset and page() uses diff --git a/IPython/core/page.py b/IPython/core/page.py index 77b226b..26edf3e 100644 --- a/IPython/core/page.py +++ b/IPython/core/page.py @@ -25,6 +25,7 @@ rid of that dependency, we could move it there. #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- +from __future__ import print_function import os import re @@ -57,18 +58,18 @@ def page_dumb(strng, start=0, screen_lines=25): out_ln = strng.splitlines()[start:] screens = chop(out_ln,screen_lines-1) if len(screens) == 1: - print >>io.stdout, os.linesep.join(screens[0]) + print(os.linesep.join(screens[0]), file=io.stdout) else: last_escape = "" for scr in screens[0:-1]: hunk = os.linesep.join(scr) - print >>io.stdout, last_escape + hunk + print(last_escape + hunk, file=io.stdout) if not page_more(): return esc_list = esc_re.findall(hunk) if len(esc_list) > 0: last_escape = esc_list[-1] - print >>io.stdout, last_escape + os.linesep.join(screens[-1]) + print(last_escape + os.linesep.join(screens[-1]), file=io.stdout) def _detect_screen_size(use_curses, screen_lines_def): """Attempt to work out the number of lines on the screen. @@ -163,7 +164,7 @@ def page(strng, start=0, screen_lines=0, pager_cmd=None): # Ugly kludge, but calling curses.initscr() flat out crashes in emacs TERM = os.environ.get('TERM','dumb') if TERM in ['dumb','emacs'] and os.name != 'nt': - print strng + print(strng) return # chop off the topmost part of the string we don't want to see str_lines = strng.splitlines()[start:] @@ -183,13 +184,13 @@ def page(strng, start=0, screen_lines=0, pager_cmd=None): try: screen_lines += _detect_screen_size(use_curses, screen_lines_def) except (TypeError, UnsupportedOperation): - print >>io.stdout, str_toprint + print(str_toprint, file=io.stdout) return #print 'numlines',numlines,'screenlines',screen_lines # dbg if numlines <= screen_lines : #print '*** normal print' # dbg - print >>io.stdout, str_toprint + print(str_toprint, file=io.stdout) else: # Try to open pager and default to internal one if that fails. # All failure modes are tagged as 'retval=1', to match the return @@ -250,7 +251,7 @@ def page_file(fname, start=0, pager_cmd=None): start -= 1 page(open(fname).read(),start) except: - print 'Unable to show file',`fname` + print('Unable to show file',repr(fname)) def get_pager_cmd(pager_cmd=None): @@ -325,13 +326,13 @@ def snip_print(str,width = 75,print_full = 0,header = ''): page(header+str) return 0 - print header, + print(header, end=' ') if len(str) < width: - print str + print(str) snip = 0 else: whalf = int((width -5)/2) - print str[:whalf] + ' <...> ' + str[-whalf:] + print(str[:whalf] + ' <...> ' + str[-whalf:]) snip = 1 if snip and print_full == 2: if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': diff --git a/IPython/core/ultratb.py b/IPython/core/ultratb.py index 93af88e..49dfb0e 100644 --- a/IPython/core/ultratb.py +++ b/IPython/core/ultratb.py @@ -1103,8 +1103,8 @@ class FormattedTB(VerboseTB, ListTB): len(self.valid_modes) self.mode = self.valid_modes[new_idx] elif mode not in self.valid_modes: - raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\ - 'Valid modes: '+str(self.valid_modes) + raise ValueError('Unrecognized mode in FormattedTB: <'+mode+'>\n' + 'Valid modes: '+str(self.valid_modes)) else: self.mode = mode # include variable details only in 'Verbose' mode @@ -1231,7 +1231,7 @@ if __name__ == "__main__": try: print spam(1, (2, 3)) except: - apply(handler, sys.exc_info() ) + handler(*sys.exc_info()) print '' handler = VerboseTB() @@ -1239,6 +1239,6 @@ if __name__ == "__main__": try: print spam(1, (2, 3)) except: - apply(handler, sys.exc_info() ) + handler(*sys.exc_info()) print '' diff --git a/IPython/extensions/autoreload.py b/IPython/extensions/autoreload.py index 9a9354a..e024594 100644 --- a/IPython/extensions/autoreload.py +++ b/IPython/extensions/autoreload.py @@ -87,6 +87,7 @@ Some of the known remaining caveats are: - C extension modules cannot be reloaded, and so cannot be autoreloaded. """ +from __future__ import print_function skip_doctest = True @@ -244,8 +245,8 @@ class ModuleReloader(object): if py_filename in self.failed: del self.failed[py_filename] except: - print >> sys.stderr, "[autoreload of %s failed: %s]" % ( - modname, traceback.format_exc(1)) + print("[autoreload of %s failed: %s]" % ( + modname, traceback.format_exc(1)), file=sys.stderr) self.failed[py_filename] = pymtime #------------------------------------------------------------------------------ diff --git a/IPython/external/decorators/_decorators.py b/IPython/external/decorators/_decorators.py index 75e2ee8..b87a455 100644 --- a/IPython/external/decorators/_decorators.py +++ b/IPython/external/decorators/_decorators.py @@ -217,7 +217,7 @@ def knownfailureif(fail_condition, msg=None): import nose def knownfailer(*args, **kwargs): if fail_val(): - raise KnownFailureTest, msg + raise KnownFailureTest(msg) else: return f(*args, **kwargs) return nose.tools.make_decorator(f)(knownfailer) diff --git a/IPython/external/pexpect/_pexpect.py b/IPython/external/pexpect/_pexpect.py index 0e6bfaa..3b8a4ea 100644 --- a/IPython/external/pexpect/_pexpect.py +++ b/IPython/external/pexpect/_pexpect.py @@ -608,11 +608,11 @@ class spawnb(object): parent_fd, child_fd = os.openpty() if parent_fd < 0 or child_fd < 0: - raise ExceptionPexpect, "Error! Could not open pty with os.openpty()." + raise ExceptionPexpect("Error! Could not open pty with os.openpty().") pid = os.fork() if pid < 0: - raise ExceptionPexpect, "Error! Failed os.fork()." + raise ExceptionPexpect("Error! Failed os.fork().") elif pid == 0: # Child. os.close(parent_fd) @@ -655,7 +655,7 @@ class spawnb(object): fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); if fd >= 0: os.close(fd) - raise ExceptionPexpect, "Error! Failed to disconnect from controlling tty. It is still possible to open /dev/tty." + raise ExceptionPexpect("Error! Failed to disconnect from controlling tty. It is still possible to open /dev/tty.") except: # Good! We are disconnected from a controlling tty. pass @@ -663,14 +663,14 @@ class spawnb(object): # Verify we can open child pty. fd = os.open(child_name, os.O_RDWR); if fd < 0: - raise ExceptionPexpect, "Error! Could not open child pty, " + child_name + raise ExceptionPexpect("Error! Could not open child pty, " + child_name) else: os.close(fd) # Verify we now have a controlling tty. fd = os.open("/dev/tty", os.O_WRONLY) if fd < 0: - raise ExceptionPexpect, "Error! Could not open controlling tty, /dev/tty" + raise ExceptionPexpect("Error! Could not open controlling tty, /dev/tty") else: os.close(fd) diff --git a/IPython/frontend/terminal/interactiveshell.py b/IPython/frontend/terminal/interactiveshell.py index 93b50ca..934b694 100644 --- a/IPython/frontend/terminal/interactiveshell.py +++ b/IPython/frontend/terminal/interactiveshell.py @@ -13,6 +13,7 @@ #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- +from __future__ import print_function import bdb import os @@ -59,8 +60,8 @@ def get_default_editor(): def get_pasted_lines(sentinel, l_input=py3compat.input): """ Yield pasted lines until the user enters the given sentinel value. """ - print "Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \ - % sentinel + print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \ + % sentinel) while True: try: l = l_input(':') @@ -69,7 +70,7 @@ def get_pasted_lines(sentinel, l_input=py3compat.input): else: yield l except EOFError: - print '' + print('') return @@ -153,7 +154,7 @@ class TerminalMagics(Magics): if name: # If storing it for further editing self.shell.user_ns[name] = SList(b.splitlines()) - print "Block assigned to '%s'" % name + print("Block assigned to '%s'" % name) else: self.shell.user_ns['pasted_block'] = b self.shell.run_cell(b) @@ -170,7 +171,7 @@ class TerminalMagics(Magics): raise UsageError( "Variable 'pasted_block' is not a string, can't execute") - print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) + print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))) self.shell.run_cell(b) @line_magic @@ -178,7 +179,7 @@ class TerminalMagics(Magics): """Toggle autoindent on/off (if available).""" self.shell.set_autoindent() - print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] + print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent]) @skip_doctest @line_magic diff --git a/IPython/lib/backgroundjobs.py b/IPython/lib/backgroundjobs.py index 8b57bea..e14feed 100644 --- a/IPython/lib/backgroundjobs.py +++ b/IPython/lib/backgroundjobs.py @@ -375,8 +375,7 @@ class BackgroundJobBase(threading.Thread): stat_dead_c = -1 def __init__(self): - raise NotImplementedError, \ - "This class can not be instantiated directly." + raise NotImplementedError("This class can not be instantiated directly.") def _init(self): """Common initialization for all BackgroundJob objects""" diff --git a/IPython/lib/demo.py b/IPython/lib/demo.py index b118fee..a8a27b4 100644 --- a/IPython/lib/demo.py +++ b/IPython/lib/demo.py @@ -168,6 +168,7 @@ print 'bye!' # the file COPYING, distributed as part of this software. # #***************************************************************************** +from __future__ import print_function import os import re @@ -318,7 +319,7 @@ class Demo(object): if index is None: if self.finished: - print >>io.stdout, 'Demo finished. Use .reset() if you want to rerun it.' + print('Demo finished. Use .reset() if you want to rerun it.', file=io.stdout) return None index = self.block_index else: @@ -387,9 +388,9 @@ class Demo(object): if index is None: return - print >>io.stdout, self.marquee('<%s> block # %s (%s remaining)' % - (self.title,index,self.nblocks-index-1)) - print >>io.stdout,(self.src_blocks_colored[index]) + print(self.marquee('<%s> block # %s (%s remaining)' % + (self.title,index,self.nblocks-index-1)), file=io.stdout) + print((self.src_blocks_colored[index]), file=io.stdout) sys.stdout.flush() def show_all(self): @@ -402,12 +403,12 @@ class Demo(object): marquee = self.marquee for index,block in enumerate(self.src_blocks_colored): if silent[index]: - print >>io.stdout, marquee('<%s> SILENT block # %s (%s remaining)' % - (title,index,nblocks-index-1)) + print(marquee('<%s> SILENT block # %s (%s remaining)' % + (title,index,nblocks-index-1)), file=io.stdout) else: - print >>io.stdout, marquee('<%s> block # %s (%s remaining)' % - (title,index,nblocks-index-1)) - print >>io.stdout, block, + print(marquee('<%s> block # %s (%s remaining)' % + (title,index,nblocks-index-1)), file=io.stdout) + print(block, end=' ', file=io.stdout) sys.stdout.flush() def run_cell(self,source): @@ -432,18 +433,18 @@ class Demo(object): next_block = self.src_blocks[index] self.block_index += 1 if self._silent[index]: - print >>io.stdout, marquee('Executing silent block # %s (%s remaining)' % - (index,self.nblocks-index-1)) + print(marquee('Executing silent block # %s (%s remaining)' % + (index,self.nblocks-index-1)), file=io.stdout) else: self.pre_cmd() self.show(index) if self.auto_all or self._auto[index]: - print >>io.stdout, marquee('output:') + print(marquee('output:'), file=io.stdout) else: - print >>io.stdout, marquee('Press to quit, to execute...'), + print(marquee('Press to quit, to execute...'), end=' ', file=io.stdout) ans = raw_input().strip() if ans: - print >>io.stdout, marquee('Block NOT executed') + print(marquee('Block NOT executed'), file=io.stdout) return try: save_argv = sys.argv @@ -462,9 +463,9 @@ class Demo(object): mq1 = self.marquee('END OF DEMO') if mq1: # avoid spurious print >>io.stdout,s if empty marquees are used - print >>io.stdout - print >>io.stdout, mq1 - print >>io.stdout, self.marquee('Use .reset() if you want to rerun it.') + print(file=io.stdout) + print(mq1, file=io.stdout) + print(self.marquee('Use .reset() if you want to rerun it.'), file=io.stdout) self.finished = True # These methods are meant to be overridden by subclasses who may wish to diff --git a/IPython/lib/irunner.py b/IPython/lib/irunner.py index 2c7e7bd..a93e68c 100755 --- a/IPython/lib/irunner.py +++ b/IPython/lib/irunner.py @@ -29,6 +29,7 @@ NOTES: - Because pexpect only works under Unix or Windows-Cygwin, this has the same limitations. This means that it will NOT work under native windows Python. """ +from __future__ import print_function # Stdlib imports import optparse @@ -248,7 +249,7 @@ class InteractiveRunner(object): if end_normal: if interact: c.send('\n') - print '<< Starting interactive mode >>', + print('<< Starting interactive mode >>', end=' ') try: c.interact() except OSError: @@ -261,7 +262,7 @@ class InteractiveRunner(object): else: if interact: e="Further interaction is not possible: child process is dead." - print >> sys.stderr, e + print(e, file=sys.stderr) # Leave the child ready for more input later on, otherwise select just # hangs on the second invocation. @@ -283,7 +284,7 @@ class InteractiveRunner(object): opts,args = parser.parse_args(argv) if len(args) != 1: - print >> sys.stderr,"You must supply exactly one file to run." + print("You must supply exactly one file to run.", file=sys.stderr) sys.exit(1) self.run_file(args[0],opts.interact) diff --git a/IPython/lib/tests/test_irunner.py b/IPython/lib/tests/test_irunner.py index bdbfd88..e3ef861 100644 --- a/IPython/lib/tests/test_irunner.py +++ b/IPython/lib/tests/test_irunner.py @@ -2,6 +2,7 @@ Not the most elegant or fine-grained, but it does cover at least the bulk functionality.""" +from __future__ import print_function # Global to make tests extra verbose and help debugging VERBOSE = True @@ -50,10 +51,10 @@ class RunnerTestCase(unittest.TestCase): if ol1 != ol2: mismatch += 1 if VERBOSE: - print '<<< line %s does not match:' % n - print repr(ol1) - print repr(ol2) - print '>>>' + print('<<< line %s does not match:' % n) + print(repr(ol1)) + print(repr(ol2)) + print('>>>') self.assert_(mismatch==0,'Number of mismatched lines: %s' % mismatch) diff --git a/IPython/lib/tests/test_irunner_pylab_magic.py b/IPython/lib/tests/test_irunner_pylab_magic.py index c7f405a..788637b 100644 --- a/IPython/lib/tests/test_irunner_pylab_magic.py +++ b/IPython/lib/tests/test_irunner_pylab_magic.py @@ -1,6 +1,7 @@ """Test suite for pylab_import_all magic Modified from the irunner module but using regex. """ +from __future__ import print_function # Global to make tests extra verbose and help debugging VERBOSE = True @@ -58,10 +59,10 @@ class RunnerTestCase(unittest.TestCase): if not re.match(ol1,ol2): mismatch += 1 if VERBOSE: - print '<<< line %s does not match:' % n - print repr(ol1) - print repr(ol2) - print '>>>' + print('<<< line %s does not match:' % n) + print(repr(ol1)) + print(repr(ol2)) + print('>>>') self.assert_(mismatch==0,'Number of mismatched lines: %s' % mismatch) diff --git a/IPython/parallel/tests/clienttest.py b/IPython/parallel/tests/clienttest.py index 478304d..1585bec 100644 --- a/IPython/parallel/tests/clienttest.py +++ b/IPython/parallel/tests/clienttest.py @@ -11,6 +11,7 @@ Authors: # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #------------------------------------------------------------------------------- +from __future__ import print_function import sys import tempfile @@ -70,13 +71,13 @@ def generate_output(): import sys from IPython.core.display import display, HTML, Math - print "stdout" - print >> sys.stderr, "stderr" + print("stdout") + print("stderr", file=sys.stderr) display(HTML("HTML")) - print "stdout2" - print >> sys.stderr, "stderr2" + print("stdout2") + print("stderr2", file=sys.stderr) display(Math(r"\alpha=\beta")) @@ -154,7 +155,7 @@ class ClusterTestCase(BaseZMQTestCase): time.sleep(0.1) self.client.spin() if not f(): - print "Warning: Awaited condition never arrived" + print("Warning: Awaited condition never arrived") def setUp(self): BaseZMQTestCase.setUp(self) @@ -180,4 +181,4 @@ class ClusterTestCase(BaseZMQTestCase): # self.context.term() # print tempfile.TemporaryFile().fileno(), # sys.stdout.flush() - \ No newline at end of file + diff --git a/IPython/testing/iptest.py b/IPython/testing/iptest.py index 654f590..be07c7b 100644 --- a/IPython/testing/iptest.py +++ b/IPython/testing/iptest.py @@ -24,6 +24,7 @@ itself from the command line. There are two ways of running this script: #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- +from __future__ import print_function # Stdlib import glob @@ -423,7 +424,7 @@ class IPTester(object): for pid in self.pids: try: - print 'Cleaning stale PID:', pid + print('Cleaning stale PID:', pid) os.kill(pid, signal.SIGKILL) except OSError: # This is just a best effort, if we fail or the process was @@ -527,8 +528,8 @@ def run_iptestall(): t_start = time.time() try: for (name, runner) in runners: - print '*'*70 - print 'IPython test group:',name + print('*'*70) + print('IPython test group:',name) res = runner.run() if res: failed.append( (name, runner) ) @@ -539,26 +540,26 @@ def run_iptestall(): nrunners = len(runners) nfail = len(failed) # summarize results - print - print '*'*70 - print 'Test suite completed for system with the following information:' - print report() - print 'Ran %s test groups in %.3fs' % (nrunners, t_tests) - print - print 'Status:' + print() + print('*'*70) + print('Test suite completed for system with the following information:') + print(report()) + print('Ran %s test groups in %.3fs' % (nrunners, t_tests)) + print() + print('Status:') if not failed: - print 'OK' + print('OK') else: # If anything went wrong, point out what command to rerun manually to # see the actual errors and individual summary - print 'ERROR - %s out of %s test groups failed.' % (nfail, nrunners) + print('ERROR - %s out of %s test groups failed.' % (nfail, nrunners)) for name, failed_runner in failed: - print '-'*40 - print 'Runner failed:',name - print 'You may wish to rerun this one individually, with:' + print('-'*40) + print('Runner failed:',name) + print('You may wish to rerun this one individually, with:') failed_call_args = [py3compat.cast_unicode(x) for x in failed_runner.call_args] - print u' '.join(failed_call_args) - print + print(u' '.join(failed_call_args)) + print() # Ensure that our exit code indicates failure sys.exit(1) diff --git a/IPython/testing/tests/test_decorators.py b/IPython/testing/tests/test_decorators.py index 5ce0a6b..9929b52 100644 --- a/IPython/testing/tests/test_decorators.py +++ b/IPython/testing/tests/test_decorators.py @@ -36,7 +36,7 @@ def getargspec(obj): elif inspect.ismethod(obj): func_obj = obj.im_func else: - raise TypeError, 'arg is not a Python function' + raise TypeError('arg is not a Python function') args, varargs, varkw = inspect.getargs(func_obj.func_code) return args, varargs, varkw, func_obj.func_defaults diff --git a/IPython/utils/PyColorize.py b/IPython/utils/PyColorize.py index fbfe9fd..f1e7369 100644 --- a/IPython/utils/PyColorize.py +++ b/IPython/utils/PyColorize.py @@ -28,11 +28,13 @@ It shows how to use the built-in keyword, token and tokenize modules to scan Python source code and re-emit it with no changes to its original formatting (which is the hard part). """ +from __future__ import print_function __all__ = ['ANSICodeColors','Parser'] _scheme_default = 'Linux' + # Imports import StringIO import keyword @@ -283,7 +285,7 @@ If no filename is given, or if filename is -, read standard input.""" try: stream = open(fname) except IOError as msg: - print >> sys.stderr, msg + print(msg, file=sys.stderr) sys.exit(1) parser = Parser() diff --git a/IPython/utils/attic.py b/IPython/utils/attic.py index 7b580a8..18d53b0 100644 --- a/IPython/utils/attic.py +++ b/IPython/utils/attic.py @@ -33,8 +33,8 @@ def mutex_opts(dict,ex_op): Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" for op1,op2 in ex_op: if op1 in dict and op2 in dict: - raise ValueError,'\n*** ERROR in Arguments *** '\ - 'Options '+op1+' and '+op2+' are mutually exclusive.' + raise ValueError('\n*** ERROR in Arguments *** '\ + 'Options '+op1+' and '+op2+' are mutually exclusive.') class EvalDict: diff --git a/IPython/utils/coloransi.py b/IPython/utils/coloransi.py index 7997ff1..51267d6 100644 --- a/IPython/utils/coloransi.py +++ b/IPython/utils/coloransi.py @@ -145,7 +145,7 @@ class ColorSchemeTable(dict): if scheme_list: if default_scheme == '': - raise ValueError,'you must specify the default color scheme' + raise ValueError('you must specify the default color scheme') for scheme in scheme_list: self.add_scheme(scheme) self.set_active_scheme(default_scheme) @@ -157,7 +157,7 @@ class ColorSchemeTable(dict): def add_scheme(self,new_scheme): """Add a new color scheme to the table.""" if not isinstance(new_scheme,ColorScheme): - raise ValueError,'ColorSchemeTable only accepts ColorScheme instances' + raise ValueError('ColorSchemeTable only accepts ColorScheme instances') self[new_scheme.name] = new_scheme def set_active_scheme(self,scheme,case_sensitive=0): @@ -176,8 +176,8 @@ class ColorSchemeTable(dict): try: scheme_idx = valid_schemes.index(scheme_test) except ValueError: - raise ValueError,'Unrecognized color scheme: ' + scheme + \ - '\nValid schemes: '+str(scheme_names).replace("'', ",'') + raise ValueError('Unrecognized color scheme: ' + scheme + \ + '\nValid schemes: '+str(scheme_names).replace("'', ",'')) else: active = scheme_names[scheme_idx] self.active_scheme_name = active diff --git a/IPython/utils/path.py b/IPython/utils/path.py index 2fed989..79cff4c 100644 --- a/IPython/utils/path.py +++ b/IPython/utils/path.py @@ -107,7 +107,7 @@ def get_py_filename(name, force_win32=None): if os.path.isfile(name): return name else: - raise IOError,'File `%r` not found.' % name + raise IOError('File `%r` not found.' % name) def filefind(filename, path_dirs=None): diff --git a/IPython/utils/tests/test_io.py b/IPython/utils/tests/test_io.py index 71244d3..ba169ba 100644 --- a/IPython/utils/tests/test_io.py +++ b/IPython/utils/tests/test_io.py @@ -11,6 +11,7 @@ #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- +from __future__ import print_function import sys @@ -33,7 +34,7 @@ def test_tee_simple(): chan = StringIO() text = 'Hello' tee = Tee(chan, channel='stdout') - print >> chan, text + print(text, file=chan) nt.assert_equal(chan.getvalue(), text+"\n") @@ -48,7 +49,7 @@ class TeeTestCase(dec.ParametricTestCase): setattr(sys, channel, trap) tee = Tee(chan, channel=channel) - print >> chan, text, + print(text, end='', file=chan) setattr(sys, channel, std_ori) trap_val = trap.getvalue() nt.assert_equals(chan.getvalue(), text) @@ -78,8 +79,8 @@ def test_capture_output(): """capture_output() context works""" with capture_output() as io: - print 'hi, stdout' - print >> sys.stderr, 'hi, stderr' + print('hi, stdout') + print('hi, stderr', file=sys.stderr) nt.assert_equals(io.stdout, 'hi, stdout\n') nt.assert_equals(io.stderr, 'hi, stderr\n') diff --git a/IPython/utils/warn.py b/IPython/utils/warn.py index d34a262..530b70b 100644 --- a/IPython/utils/warn.py +++ b/IPython/utils/warn.py @@ -13,6 +13,7 @@ Utilities for warnings. Shoudn't we just use the built in warnings module. #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- +from __future__ import print_function import sys @@ -43,7 +44,7 @@ def warn(msg,level=2,exit_val=1): header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] io.stderr.write('%s%s' % (header[level],msg)) if level == 4: - print >> io.stderr,'Exiting.\n' + print('Exiting.\n', file=io.stderr) sys.exit(exit_val) diff --git a/IPython/zmq/frontend.py b/IPython/zmq/frontend.py index 79899dc..22f7b38 100755 --- a/IPython/zmq/frontend.py +++ b/IPython/zmq/frontend.py @@ -5,6 +5,8 @@ #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- +from __future__ import print_function + # stdlib import cPickle as pickle import code @@ -57,25 +59,25 @@ class Console(code.InteractiveConsole): return c = omsg.content.code.rstrip() if c: - print '[IN from %s]' % omsg.parent_header.username - print c + print('[IN from %s]' % omsg.parent_header.username) + print(c) def handle_pyout(self, omsg): #print omsg # dbg if omsg.parent_header.session == self.session.session: - print "%s%s" % (sys.ps3, omsg.content.data) + print("%s%s" % (sys.ps3, omsg.content.data)) else: - print '[Out from %s]' % omsg.parent_header.username - print omsg.content.data + print('[Out from %s]' % omsg.parent_header.username) + print(omsg.content.data) def print_pyerr(self, err): - print >> sys.stderr, err.etype,':', err.evalue - print >> sys.stderr, ''.join(err.traceback) + print(err.etype,':', err.evalue, file=sys.stderr) + print(''.join(err.traceback), file=sys.stderr) def handle_pyerr(self, omsg): if omsg.parent_header.session == self.session.session: return - print >> sys.stderr, '[ERR from %s]' % omsg.parent_header.username + print('[ERR from %s]' % omsg.parent_header.username, file=sys.stderr) self.print_pyerr(omsg.content) def handle_stream(self, omsg): @@ -83,8 +85,8 @@ class Console(code.InteractiveConsole): outstream = sys.stdout else: outstream = sys.stderr - print >> outstream, '*ERR*', - print >> outstream, omsg.content.data, + print('*ERR*', end=' ', file=outstream) + print(omsg.content.data, end=' ', file=outstream) def handle_output(self, omsg): handler = self.handlers.get(omsg.msg_type, None) @@ -107,12 +109,12 @@ class Console(code.InteractiveConsole): if rep.content.status == 'error': self.print_pyerr(rep.content) elif rep.content.status == 'aborted': - print >> sys.stderr, "ERROR: ABORTED" + print("ERROR: ABORTED", file=sys.stderr) ab = self.messages[rep.parent_header.msg_id].content if 'code' in ab: - print >> sys.stderr, ab.code + print(ab.code, file=sys.stderr) else: - print >> sys.stderr, ab + print(ab, file=sys.stderr) def recv_reply(self): ident,rep = self.session.recv(self.request_socket) @@ -153,7 +155,7 @@ class Console(code.InteractiveConsole): time.sleep(0.05) else: # We exited without hearing back from the kernel! - print >> sys.stderr, 'ERROR!!! kernel never got back to us!!!' + print('ERROR!!! kernel never got back to us!!!', file=sys.stderr) class InteractiveClient(object): diff --git a/docs/examples/parallel/interengine/bintree.py b/docs/examples/parallel/interengine/bintree.py index ca6db6f..66e1236 100644 --- a/docs/examples/parallel/interengine/bintree.py +++ b/docs/examples/parallel/interengine/bintree.py @@ -6,6 +6,7 @@ use from bintree_script.py Provides parallel [all]reduce functionality """ +from __future__ import print_function import cPickle as pickle import re @@ -92,7 +93,7 @@ def depth(n, tree): def print_bintree(tree, indent=' '): """print a binary tree""" for n in sorted(tree.keys()): - print "%s%s" % (indent * depth(n,tree), n) + print("%s%s" % (indent * depth(n,tree), n)) #---------------------------------------------------------------------------- # Communicator class for a binary-tree map diff --git a/setup.py b/setup.py index c6f5b2a..0e80ab5 100755 --- a/setup.py +++ b/setup.py @@ -270,6 +270,8 @@ if 'setuptools' in sys.modules: # anything. setuptools_extra_args['use_2to3_exclude_fixers'] = [ 'lib2to3.fixes.fix_except', + 'lib2to3.fixes.fix_apply', + 'lib2to3.fixes.fix_repr', ] from setuptools.command.build_py import build_py setup_args['cmdclass'] = {'build_py': record_commit_info('IPython', build_cmd=build_py)}