From e6afea5170f5e5e3fde5aa4cb637e18c588f4b4e 2013-10-29 16:14:15 From: Thomas Kluyver Date: 2013-10-29 16:14:15 Subject: [PATCH] Convert print statements to print function calls libmodernize.fixes.fix_print --- diff --git a/IPython/config/application.py b/IPython/config/application.py index c2e5bd9..1e7c32f 100644 --- a/IPython/config/application.py +++ b/IPython/config/application.py @@ -7,6 +7,7 @@ Authors: * Brian Granger * Min RK """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team @@ -286,7 +287,7 @@ class Application(SingletonConfigurable): help[0] = help[0].replace('--%s='%alias, '-%s '%alias) lines.extend(help) # lines.append('') - print os.linesep.join(lines) + print(os.linesep.join(lines)) def print_flag_help(self): """Print the flag part of the help.""" @@ -299,7 +300,7 @@ class Application(SingletonConfigurable): lines.append(prefix+m) lines.append(indent(dedent(help.strip()))) # lines.append('') - print os.linesep.join(lines) + print(os.linesep.join(lines)) def print_options(self): if not self.flags and not self.aliases: @@ -310,10 +311,10 @@ class Application(SingletonConfigurable): for p in wrap_paragraphs(self.option_description): lines.append(p) lines.append('') - print os.linesep.join(lines) + print(os.linesep.join(lines)) self.print_flag_help() self.print_alias_help() - print + print() def print_subcommands(self): """Print the subcommand part of the help.""" @@ -331,7 +332,7 @@ class Application(SingletonConfigurable): if help: lines.append(indent(dedent(help.strip()))) lines.append('') - print os.linesep.join(lines) + print(os.linesep.join(lines)) def print_help(self, classes=False): """Print the help for each Configurable class in self.classes. @@ -344,19 +345,19 @@ class Application(SingletonConfigurable): if classes: if self.classes: - print "Class parameters" - print "----------------" - print + print("Class parameters") + print("----------------") + print() for p in wrap_paragraphs(self.keyvalue_description): - print p - print + print(p) + print() for cls in self.classes: cls.class_print_help() - print + print() else: - print "To see all available configurables, use `--help-all`" - print + print("To see all available configurables, use `--help-all`") + print() self.print_examples() @@ -364,8 +365,8 @@ class Application(SingletonConfigurable): def print_description(self): """Print the application description.""" for p in wrap_paragraphs(self.description): - print p - print + print(p) + print() def print_examples(self): """Print usage and examples. @@ -374,15 +375,15 @@ class Application(SingletonConfigurable): and should contain examples of the application's usage. """ if self.examples: - print "Examples" - print "--------" - print - print indent(dedent(self.examples.strip())) - print + print("Examples") + print("--------") + print() + print(indent(dedent(self.examples.strip()))) + print() def print_version(self): """Print the version string.""" - print self.version + print(self.version) def update_config(self, config): """Fire the traits events when the config is updated.""" diff --git a/IPython/config/configurable.py b/IPython/config/configurable.py index 60f79e9..35d2ad4 100644 --- a/IPython/config/configurable.py +++ b/IPython/config/configurable.py @@ -13,6 +13,7 @@ Authors: * Fernando Perez * Min RK """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team @@ -236,7 +237,7 @@ class Configurable(HasTraits): @classmethod def class_print_help(cls, inst=None): """Get the help string for a single trait and print it.""" - print cls.class_get_help(inst) + print(cls.class_get_help(inst)) @classmethod def class_config_section(cls): diff --git a/IPython/core/logger.py b/IPython/core/logger.py index 1c21b21..0b51285 100644 --- a/IPython/core/logger.py +++ b/IPython/core/logger.py @@ -1,5 +1,6 @@ """Logger class for IPython's logging facilities. """ +from __future__ import print_function #***************************************************************************** # Copyright (C) 2001 Janko Hauser and @@ -137,33 +138,33 @@ class Logger(object): label = {0:'OFF',1:'ON',False:'OFF',True:'ON'} if self.logfile is None: - print """ + print(""" Logging hasn't been started yet (use logstart for that). %logon/%logoff are for temporarily starting and stopping logging for a logfile which already exists. But you must first start the logging process with -%logstart (optionally giving a logfile name).""" +%logstart (optionally giving a logfile name).""") else: if self.log_active == val: - print 'Logging is already',label[val] + print('Logging is already',label[val]) else: - print 'Switching logging',label[val] + print('Switching logging',label[val]) self.log_active = not self.log_active self.log_active_out = self.log_active def logstate(self): """Print a status message about the logger.""" if self.logfile is None: - print 'Logging has not been activated.' + print('Logging has not been activated.') else: state = self.log_active and 'active' or 'temporarily suspended' - print 'Filename :',self.logfname - print 'Mode :',self.logmode - print 'Output logging :',self.log_output - print 'Raw input log :',self.log_raw_input - print 'Timestamping :',self.timestamp - print 'State :',state + print('Filename :',self.logfname) + print('Mode :',self.logmode) + print('Output logging :',self.log_output) + print('Raw input log :',self.log_raw_input) + print('Timestamping :',self.timestamp) + print('State :',state) def log(self, line_mod, line_ori): """Write the sources to a log. @@ -213,7 +214,7 @@ which already exists. But you must first start the logging process with self.logfile.close() self.logfile = None else: - print "Logging hadn't been started." + print("Logging hadn't been started.") self.log_active = False # For backwards compatibility, in case anyone was using this. diff --git a/IPython/core/magic.py b/IPython/core/magic.py index 77a4ec9..e265702 100644 --- a/IPython/core/magic.py +++ b/IPython/core/magic.py @@ -1,6 +1,7 @@ # encoding: utf-8 """Magic functions for InteractiveShell. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2001 Janko Hauser and @@ -544,8 +545,8 @@ class Magics(Configurable): def arg_err(self,func): """Print docstring if incorrect arguments were passed""" - print 'Error in arguments:' - print oinspect.getdoc(func) + print('Error in arguments:') + print(oinspect.getdoc(func)) def format_latex(self, strng): """Format a string for latex inclusion.""" diff --git a/IPython/core/magics/auto.py b/IPython/core/magics/auto.py index 04aff30..fac5d1f 100644 --- a/IPython/core/magics/auto.py +++ b/IPython/core/magics/auto.py @@ -1,5 +1,6 @@ """Implementation of magic functions that control various automatic behaviors. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -57,7 +58,7 @@ class AutoMagics(Magics): else: val = not mman.auto_magic mman.auto_magic = val - print '\n' + self.shell.magics_manager.auto_status() + print('\n' + self.shell.magics_manager.auto_status()) @skip_doctest @line_magic @@ -125,4 +126,4 @@ class AutoMagics(Magics): except AttributeError: self.shell.autocall = self._magic_state.autocall_save = 1 - print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] + print("Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]) diff --git a/IPython/core/magics/code.py b/IPython/core/magics/code.py index 9327005..cd072d1 100644 --- a/IPython/core/magics/code.py +++ b/IPython/core/magics/code.py @@ -1,5 +1,6 @@ """Implementation of code management magic functions. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -189,15 +190,15 @@ class CodeMagics(Magics): try: overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n') except StdinNotImplementedError: - print "File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s) + print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s)) return if not overwrite : - print 'Operation cancelled.' + print('Operation cancelled.') return try: cmds = self.shell.find_user_code(codefrom,raw) except (TypeError, ValueError) as e: - print e.args[0] + print(e.args[0]) return out = py3compat.cast_unicode(cmds) with io.open(fname, mode, encoding="utf-8") as f: @@ -207,8 +208,8 @@ class CodeMagics(Magics): # make sure we end on a newline if not out.endswith(u'\n'): f.write(u'\n') - print 'The following commands were written to file `%s`:' % fname - print cmds + print('The following commands were written to file `%s`:' % fname) + print(cmds) @line_magic def pastebin(self, parameter_s=''): @@ -230,7 +231,7 @@ class CodeMagics(Magics): try: code = self.shell.find_user_code(args) except (ValueError, TypeError) as e: - print e.args[0] + print(e.args[0]) return from urllib2 import urlopen # Deferred import @@ -337,7 +338,7 @@ class CodeMagics(Magics): ans = True if ans is False : - print 'Operation cancelled.' + print('Operation cancelled.') return self.shell.set_next_input(contents) @@ -459,7 +460,7 @@ class CodeMagics(Magics): if use_temp: filename = shell.mktempfile(data) - print 'IPython will make a temporary file named:',filename + print('IPython will make a temporary file named:',filename) # use last_call to remember the state of the previous call, but don't # let it be clobbered by successive '-p' calls. @@ -637,7 +638,7 @@ class CodeMagics(Magics): self._edit_macro(args, e.args[0]) return except InteractivelyDefined as e: - print "Editing In[%i]" % e.index + print("Editing In[%i]" % e.index) args = str(e.index) filename, lineno, is_temp = self._find_edit_target(self.shell, args, opts, last_call) @@ -647,7 +648,7 @@ class CodeMagics(Magics): return # do actual editing here - print 'Editing...', + print('Editing...', end=' ') sys.stdout.flush() try: # Quote filenames that may have spaces in them @@ -665,9 +666,9 @@ class CodeMagics(Magics): self.shell.user_ns['pasted_block'] = f.read() if 'x' in opts: # -x prevents actual execution - print + print() else: - print 'done. Executing edited code...' + print('done. Executing edited code...') with preserve_keys(self.shell.user_ns, '__file__'): if not is_temp: self.shell.user_ns['__file__'] = filename diff --git a/IPython/core/magics/config.py b/IPython/core/magics/config.py index 0092b3d..39a493f 100644 --- a/IPython/core/magics/config.py +++ b/IPython/core/magics/config.py @@ -1,5 +1,6 @@ """Implementation of configuration-related magic functions. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -116,9 +117,9 @@ class ConfigMagics(Magics): line = s.strip() if not line: # print available configurable names - print "Available objects for config:" + print("Available objects for config:") for name in classnames: - print " ", name + print(" ", name) return elif line in classnames: # `%config TerminalInteractiveShell` will print trait info for @@ -128,7 +129,7 @@ class ConfigMagics(Magics): help = cls.class_get_help(c) # strip leading '--' from cl-args: help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) - print help + print(help) return elif reg.match(line): cls, attr = line.split('.') diff --git a/IPython/core/magics/deprecated.py b/IPython/core/magics/deprecated.py index 254b101..04da498 100644 --- a/IPython/core/magics/deprecated.py +++ b/IPython/core/magics/deprecated.py @@ -1,5 +1,6 @@ """Deprecated Magic functions. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -26,20 +27,20 @@ class DeprecatedMagics(Magics): @line_magic def install_profiles(self, parameter_s=''): """%install_profiles has been deprecated.""" - print '\n'.join([ + print('\n'.join([ "%install_profiles has been deprecated.", "Use `ipython profile list` to view available profiles.", "Requesting a profile with `ipython profile create `", "or `ipython --profile=` will start with the bundled", "profile of that name if it exists." - ]) + ])) @line_magic def install_default_config(self, parameter_s=''): """%install_default_config has been deprecated.""" - print '\n'.join([ + print('\n'.join([ "%install_default_config has been deprecated.", "Use `ipython profile create ` to initialize a profile", "with the default config files.", "Add `--reset` to overwrite already existing config files with defaults." - ]) + ])) diff --git a/IPython/core/magics/execution.py b/IPython/core/magics/execution.py index f5614ab..692519f 100644 --- a/IPython/core/magics/execution.py +++ b/IPython/core/magics/execution.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- """Implementation of execution-related magic functions. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -277,22 +278,22 @@ python-profiler package from non-free.""") if 'q' not in opts: page.page(output) - print sys_exit, + print(sys_exit, end=' ') dump_file = opts.D[0] text_file = opts.T[0] if dump_file: dump_file = unquote_filename(dump_file) prof.dump_stats(dump_file) - print '\n*** Profile stats marshalled to file',\ - repr(dump_file)+'.',sys_exit + print('\n*** Profile stats marshalled to file',\ + 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',\ - repr(text_file)+'.',sys_exit + print('\n*** Profile printout saved to text file',\ + repr(text_file)+'.',sys_exit) if 'r' in opts: return stats @@ -332,7 +333,7 @@ python-profiler package from non-free.""") # set on the shell self.shell.call_pdb = new_pdb - print 'Automatic pdb calling has been turned',on_off(new_pdb) + print('Automatic pdb calling has been turned',on_off(new_pdb)) @skip_doctest @magic_arguments.magic_arguments() @@ -558,7 +559,7 @@ python-profiler package from non-free.""") filename = file_finder(arg_lst[0]) except IndexError: warn('you must provide at least a filename.') - print '\n%run:\n', oinspect.getdoc(self.run) + print('\n%run:\n', oinspect.getdoc(self.run)) return except IOError as e: try: @@ -775,7 +776,7 @@ python-profiler package from non-free.""") deb.mainpyfile = deb.canonic(filename) # Start file run - print "NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt + print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt) try: if filename: # save filename so it can be used by methods on the deb object @@ -809,9 +810,9 @@ python-profiler package from non-free.""") t1 = clock2() t_usr = t1[0] - t0[0] t_sys = t1[1] - t0[1] - print "\nIPython CPU timings (estimated):" - print " User : %10.2f s." % t_usr - print " System : %10.2f s." % t_sys + print("\nIPython CPU timings (estimated):") + print(" User : %10.2f s." % t_usr) + print(" System : %10.2f s." % t_sys) else: runs = range(nruns) t0 = clock2() @@ -820,13 +821,13 @@ python-profiler package from non-free.""") t1 = clock2() t_usr = t1[0] - t0[0] t_sys = t1[1] - t0[1] - print "\nIPython CPU timings (estimated):" - print "Total runs performed:", nruns - print " Times : %10s %10s" % ('Total', 'Per run') - print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) - print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) + print("\nIPython CPU timings (estimated):") + print("Total runs performed:", nruns) + print(" Times : %10s %10s" % ('Total', 'Per run')) + print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)) + print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)) twall1 = time.time() - print "Wall time: %10.2f s." % (twall1 - twall0) + print("Wall time: %10.2f s." % (twall1 - twall0)) @skip_doctest @line_cell_magic @@ -989,10 +990,10 @@ python-profiler package from non-free.""") all_runs = timer.repeat(repeat, number) best = min(all_runs) / number if not quiet : - print u"%d loops, best of %d: %s per loop" % (number, repeat, - _format_time(best, precision)) + print(u"%d loops, best of %d: %s per loop" % (number, repeat, + _format_time(best, precision))) if tc > tc_min: - print "Compiler time: %.2f s" % tc + print("Compiler time: %.2f s" % tc) if return_result: return TimeitResult(number, repeat, best, all_runs, tc, precision) @@ -1110,13 +1111,13 @@ python-profiler package from non-free.""") cpu_tot = cpu_user+cpu_sys # On windows cpu_sys is always zero, so no new information to the next print if sys.platform != 'win32': - print "CPU times: user %s, sys: %s, total: %s" % \ - (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)) - print "Wall time: %s" % _format_time(wall_time) + print("CPU times: user %s, sys: %s, total: %s" % \ + (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))) + print("Wall time: %s" % _format_time(wall_time)) if tc > tc_min: - print "Compiler : %s" % _format_time(tc) + print("Compiler : %s" % _format_time(tc)) if tp > tp_min: - print "Parser : %s" % _format_time(tp) + print("Parser : %s" % _format_time(tp)) return out @skip_doctest @@ -1195,14 +1196,14 @@ python-profiler package from non-free.""") try: lines = self.shell.find_user_code(codefrom, 'r' in opts) except (ValueError, TypeError) as e: - print e.args[0] + print(e.args[0]) return macro = Macro(lines) self.shell.define_macro(name, macro) if not ( 'q' in opts) : - print 'Macro `%s` created. To execute, type its name (without quotes).' % name - print '=== Macro contents: ===' - print macro, + print('Macro `%s` created. To execute, type its name (without quotes).' % name) + print('=== Macro contents: ===') + print(macro, end=' ') @magic_arguments.magic_arguments() @magic_arguments.argument('output', type=str, default='', nargs='?', diff --git a/IPython/core/magics/extension.py b/IPython/core/magics/extension.py index 31356b0..7ef4695 100644 --- a/IPython/core/magics/extension.py +++ b/IPython/core/magics/extension.py @@ -1,5 +1,6 @@ """Implementation of magic functions for the extension machinery. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -46,12 +47,12 @@ class ExtensionMagics(Magics): filename = self.shell.extension_manager.install_extension(args, opts.get('n')) except ValueError as e: - print e + print(e) return filename = os.path.basename(filename) - print "Installed %s. To use it, type:" % filename - print " %%load_ext %s" % os.path.splitext(filename)[0] + print("Installed %s. To use it, type:" % filename) + print(" %%load_ext %s" % os.path.splitext(filename)[0]) @line_magic @@ -62,10 +63,10 @@ class ExtensionMagics(Magics): res = self.shell.extension_manager.load_extension(module_str) if res == 'already loaded': - print "The %s extension is already loaded. To reload it, use:" % module_str - print " %reload_ext", module_str + print("The %s extension is already loaded. To reload it, use:" % module_str) + print(" %reload_ext", module_str) elif res == 'no load function': - print "The %s module is not an IPython extension." % module_str + print("The %s module is not an IPython extension." % module_str) @line_magic def unload_ext(self, module_str): @@ -80,9 +81,9 @@ class ExtensionMagics(Magics): res = self.shell.extension_manager.unload_extension(module_str) if res == 'no unload function': - print "The %s extension doesn't define how to unload it." % module_str + print("The %s extension doesn't define how to unload it." % module_str) elif res == "not loaded": - print "The %s extension is not loaded." % module_str + print("The %s extension is not loaded." % module_str) @line_magic def reload_ext(self, module_str): diff --git a/IPython/core/magics/namespace.py b/IPython/core/magics/namespace.py index 1d031dc..2909f6a 100644 --- a/IPython/core/magics/namespace.py +++ b/IPython/core/magics/namespace.py @@ -1,5 +1,6 @@ """Implementation of namespace-related magic functions. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -117,7 +118,7 @@ class NamespaceMagics(Magics): try: filename = get_py_filename(parameter_s) except IOError as msg: - print msg + print(msg) return page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False))) @@ -204,7 +205,7 @@ class NamespaceMagics(Magics): try: parameter_s.encode('ascii') except UnicodeEncodeError: - print 'Python identifiers can only contain ascii characters.' + print('Python identifiers can only contain ascii characters.') return # default namespaces to be searched @@ -327,20 +328,20 @@ class NamespaceMagics(Magics): varlist = self.who_ls(parameter_s) if not varlist: if parameter_s: - print 'No variables match your requested type.' + print('No variables match your requested type.') else: - print 'Interactive namespace is empty.' + print('Interactive namespace is empty.') return # if we have variables, move on... count = 0 for i in varlist: - print i+'\t', + print(i+'\t', end=' ') count += 1 if count > 8: count = 0 - print - print + print() + print() @skip_doctest @line_magic @@ -378,9 +379,9 @@ class NamespaceMagics(Magics): varnames = self.who_ls(parameter_s) if not varnames: if parameter_s: - print 'No variables match your requested type.' + print('No variables match your requested type.') else: - print 'Interactive namespace is empty.' + print('Interactive namespace is empty.') return # if we have variables, move on... @@ -432,15 +433,15 @@ class NamespaceMagics(Magics): varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep # table header - print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ - ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) + print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ + ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)) # and the table itself kb = 1024 Mb = 1048576 # kb**2 for vname,var,vtype in zip(varnames,varlist,typelist): - print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), + print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ') if vtype in seq_types: - print "n="+str(len(var)) + print("n="+str(len(var))) elif vtype == ndarray_type: vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] if vtype==ndarray_type: @@ -450,13 +451,13 @@ class NamespaceMagics(Magics): vdtype = var.dtype if vbytes < 100000: - print aformat % (vshape, vsize, vdtype, vbytes) + print(aformat % (vshape, vsize, vdtype, vbytes)) else: - print aformat % (vshape, vsize, vdtype, vbytes), + print(aformat % (vshape, vsize, vdtype, vbytes), end=' ') if vbytes < Mb: - print '(%s kb)' % (vbytes/kb,) + print('(%s kb)' % (vbytes/kb,)) else: - print '(%s Mb)' % (vbytes/Mb,) + print('(%s Mb)' % (vbytes/Mb,)) else: try: vstr = str(var) @@ -467,9 +468,9 @@ class NamespaceMagics(Magics): vstr = "" % id(var) vstr = vstr.replace('\n', '\\n') if len(vstr) < 50: - print vstr + print(vstr) else: - print vstr[:25] + "<...>" + vstr[-25:] + print(vstr[:25] + "<...>" + vstr[-25:]) @line_magic def reset(self, parameter_s=''): @@ -540,7 +541,7 @@ class NamespaceMagics(Magics): except StdinNotImplementedError: ans = True if not ans: - print 'Nothing done.' + print('Nothing done.') return if 's' in opts: # Soft reset @@ -557,11 +558,11 @@ class NamespaceMagics(Magics): for target in args: target = target.lower() # make matches case insensitive if target == 'out': - print "Flushing output cache (%d entries)" % len(user_ns['_oh']) + print("Flushing output cache (%d entries)" % len(user_ns['_oh'])) self.shell.displayhook.flush() elif target == 'in': - print "Flushing input history" + print("Flushing input history") pc = self.shell.displayhook.prompt_count + 1 for n in range(1, pc): key = '_i'+repr(n) @@ -585,15 +586,15 @@ class NamespaceMagics(Magics): if isinstance(val,ndarray): del user_ns[x] except ImportError: - print "reset array only works if Numpy is available." + print("reset array only works if Numpy is available.") elif target == 'dhist': - print "Flushing directory history" + print("Flushing directory history") del user_ns['_dh'][:] else: - print "Don't know how to reset ", - print target + ", please run `%reset?` for details" + print("Don't know how to reset ", end=' ') + print(target + ", please run `%reset?` for details") gc.collect() @@ -670,11 +671,11 @@ class NamespaceMagics(Magics): except StdinNotImplementedError: ans = True if not ans: - print 'Nothing done.' + print('Nothing done.') return user_ns = self.shell.user_ns if not regex: - print 'No regex pattern specified. Nothing done.' + print('No regex pattern specified. Nothing done.') return else: try: @@ -701,4 +702,4 @@ class NamespaceMagics(Magics): try: self.shell.del_var(varname, ('n' in opts)) except (NameError, ValueError) as e: - print type(e).__name__ +": "+ str(e) + print(type(e).__name__ +": "+ str(e)) diff --git a/IPython/core/magics/osm.py b/IPython/core/magics/osm.py index 3cfc0f0..1a048ac 100644 --- a/IPython/core/magics/osm.py +++ b/IPython/core/magics/osm.py @@ -3,6 +3,7 @@ Note: this module is named 'osm' instead of 'os' to avoid a collision with the builtin. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -107,7 +108,7 @@ class OSMagics(Magics): # for k, v in stored: # atab.append(k, v[0]) - print "Total number of aliases:", len(aliases) + print("Total number of aliases:", len(aliases)) sys.stdout.flush() return aliases @@ -115,7 +116,7 @@ class OSMagics(Magics): try: alias,cmd = par.split(None, 1) except TypeError: - print(oinspect.getdoc(self.alias)) + print((oinspect.getdoc(self.alias))) return try: @@ -137,7 +138,7 @@ class OSMagics(Magics): stored = self.shell.db.get('stored_aliases', {} ) if aname in stored: - print "Removing %stored alias",aname + print("Removing %stored alias",aname) del stored[aname] self.shell.db['stored_aliases'] = stored @@ -284,7 +285,7 @@ class OSMagics(Magics): try: ps = self.shell.user_ns['_dh'][nn] except IndexError: - print 'The requested directory does not exist in history.' + print('The requested directory does not exist in history.') return else: opts = {} @@ -307,7 +308,7 @@ class OSMagics(Magics): ps = fallback if ps is None: - print "No matching entry in directory history" + print("No matching entry in directory history") return else: opts = {} @@ -331,7 +332,7 @@ class OSMagics(Magics): if ps in bkms: target = bkms[ps] - print '(bookmark:%s) -> %s' % (ps, target) + print('(bookmark:%s) -> %s' % (ps, target)) ps = target else: if 'b' in opts: @@ -347,7 +348,7 @@ class OSMagics(Magics): if hasattr(self.shell, 'term_title') and self.shell.term_title: set_term_title('IPython: ' + abbrev_cwd()) except OSError: - print sys.exc_info()[1] + print(sys.exc_info()[1]) else: cwd = os.getcwdu() dhist = self.shell.user_ns['_dh'] @@ -366,7 +367,7 @@ class OSMagics(Magics): dhist.append(cwd) self.shell.db['dhist'] = compress_dhist(dhist)[-100:] if not 'q' in opts and self.shell.user_ns['_dh']: - print self.shell.user_ns['_dh'][-1] + print(self.shell.user_ns['_dh'][-1]) @line_magic @@ -399,7 +400,7 @@ class OSMagics(Magics): raise UsageError("%popd on empty stack") top = self.shell.dir_stack.pop(0) self.cd(top) - print "popd ->",top + print("popd ->",top) @line_magic def dirs(self, parameter_s=''): @@ -441,9 +442,9 @@ class OSMagics(Magics): return else: ini,fin = 0,len(dh) - print 'Directory history (kept in _dh)' + print('Directory history (kept in _dh)') for i in range(ini, fin): - print "%d: %s" % (i, dh[i]) + print("%d: %s" % (i, dh[i])) @skip_doctest @line_magic @@ -555,7 +556,7 @@ class OSMagics(Magics): split = 'l' in opts out = self.shell.getoutput(cmd, split=split) if 'v' in opts: - print '%s ==\n%s' % (var, pformat(out)) + print('%s ==\n%s' % (var, pformat(out))) if var: self.shell.user_ns.update({var:out}) else: @@ -667,9 +668,9 @@ class OSMagics(Magics): else: size = 0 fmt = '%-'+str(size)+'s -> %s' - print 'Current bookmarks:' + print('Current bookmarks:') for bk in bks: - print fmt % (bk, bkms[bk]) + print(fmt % (bk, bkms[bk])) else: if not args: raise UsageError("%bookmark: You must specify the bookmark name") @@ -701,7 +702,7 @@ class OSMagics(Magics): try : cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False) except (ValueError, IOError): - print "Error: no such file, variable, URL, history range or macro" + print("Error: no such file, variable, URL, history range or macro") return page.page(self.shell.pycolorize(source_to_unicode(cont))) @@ -727,11 +728,11 @@ class OSMagics(Magics): if os.path.exists(filename): if args.append: - print "Appending to %s" % filename + print("Appending to %s" % filename) else: - print "Overwriting %s" % filename + print("Overwriting %s" % filename) else: - print "Writing %s" % filename + print("Writing %s" % filename) mode = 'a' if args.append else 'w' with io.open(filename, mode, encoding='utf-8') as f: diff --git a/IPython/core/magics/pylab.py b/IPython/core/magics/pylab.py index 8e0f980..5c5887e 100644 --- a/IPython/core/magics/pylab.py +++ b/IPython/core/magics/pylab.py @@ -1,5 +1,6 @@ """Implementation of magic functions for matplotlib/pylab support. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -139,5 +140,5 @@ class PylabMagics(Magics): def _show_matplotlib_backend(self, gui, backend): """show matplotlib message backend message""" if not gui or gui == 'auto': - print ("Using matplotlib backend: %s" % backend) + print(("Using matplotlib backend: %s" % backend)) diff --git a/IPython/core/magics/script.py b/IPython/core/magics/script.py index 2300876..02ff627 100644 --- a/IPython/core/magics/script.py +++ b/IPython/core/magics/script.py @@ -1,4 +1,5 @@ """Magic functions for running cells in various scripts.""" +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -186,7 +187,7 @@ class ScriptMagics(Magics): p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE) except OSError as e: if e.errno == errno.ENOENT: - print "Couldn't find program: %r" % cmd[0] + print("Couldn't find program: %r" % cmd[0]) return else: raise @@ -211,20 +212,20 @@ class ScriptMagics(Magics): p.send_signal(signal.SIGINT) time.sleep(0.1) if p.poll() is not None: - print "Process is interrupted." + print("Process is interrupted.") return p.terminate() time.sleep(0.1) if p.poll() is not None: - print "Process is terminated." + print("Process is terminated.") return p.kill() - print "Process is killed." + print("Process is killed.") except OSError: pass except Exception as e: - print "Error while terminating subprocess (pid=%i): %s" \ - % (p.pid, e) + print("Error while terminating subprocess (pid=%i): %s" \ + % (p.pid, e)) return out = py3compat.bytes_to_str(out) err = py3compat.bytes_to_str(err) @@ -249,7 +250,7 @@ class ScriptMagics(Magics): def killbgscripts(self, _nouse_=''): """Kill all BG processes started by %%script and its family.""" self.kill_bg_processes() - print "All background processes were killed." + print("All background processes were killed.") def kill_bg_processes(self): """Kill all BG processes which are still running.""" diff --git a/IPython/core/profileapp.py b/IPython/core/profileapp.py index 0e93659..bce93ff 100644 --- a/IPython/core/profileapp.py +++ b/IPython/core/profileapp.py @@ -9,6 +9,7 @@ Authors: * Min RK """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2008 The IPython Development Team @@ -129,7 +130,7 @@ class ProfileLocate(BaseIPythonApplication): self.profile = self.extra_args[0] def start(self): - print self.profile_dir.location + print(self.profile_dir.location) class ProfileList(Application): @@ -160,35 +161,35 @@ class ProfileList(Application): def _print_profiles(self, profiles): """print list of profiles, indented.""" for profile in profiles: - print ' %s' % profile + print(' %s' % profile) def list_profile_dirs(self): profiles = list_bundled_profiles() if profiles: - print - print "Available profiles in IPython:" + print() + print("Available profiles in IPython:") self._print_profiles(profiles) - print - print " The first request for a bundled profile will copy it" - print " into your IPython directory (%s)," % self.ipython_dir - print " where you can customize it." + print() + print(" The first request for a bundled profile will copy it") + print(" into your IPython directory (%s)," % self.ipython_dir) + print(" where you can customize it.") profiles = list_profiles_in(self.ipython_dir) if profiles: - print - print "Available profiles in %s:" % self.ipython_dir + print() + print("Available profiles in %s:" % self.ipython_dir) self._print_profiles(profiles) profiles = list_profiles_in(os.getcwdu()) if profiles: - print - print "Available profiles in current directory (%s):" % os.getcwdu() + print() + print("Available profiles in current directory (%s):" % os.getcwdu()) self._print_profiles(profiles) - print - print "To use any of the above profiles, start IPython with:" - print " ipython --profile=" - print + print() + print("To use any of the above profiles, start IPython with:") + print(" ipython --profile=") + print() def start(self): self.list_profile_dirs() @@ -304,8 +305,8 @@ class ProfileApp(Application): def start(self): if self.subapp is None: - print "No subcommand specified. Must specify one of: %s"%(self.subcommands.keys()) - print + print("No subcommand specified. Must specify one of: %s"%(self.subcommands.keys())) + print() self.print_description() self.print_subcommands() self.exit(1) diff --git a/IPython/core/pylabtools.py b/IPython/core/pylabtools.py index b6d9bf7..f1bc1ee 100644 --- a/IPython/core/pylabtools.py +++ b/IPython/core/pylabtools.py @@ -7,6 +7,7 @@ Authors * Fernando Perez. * Brian Granger """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2009 The IPython Development Team @@ -74,7 +75,7 @@ def getfigs(*fig_nums): for num in fig_nums: f = Gcf.figs.get(num) if f is None: - print('Warning: figure %s not available.' % num) + print(('Warning: figure %s not available.' % num)) else: figs.append(f.canvas.figure) return figs diff --git a/IPython/core/shellapp.py b/IPython/core/shellapp.py index 032dd97..b7b515d 100644 --- a/IPython/core/shellapp.py +++ b/IPython/core/shellapp.py @@ -21,6 +21,7 @@ Authors #----------------------------------------------------------------------------- from __future__ import absolute_import +from __future__ import print_function import glob import os @@ -248,7 +249,7 @@ class InteractiveShellApp(Configurable): self.log.info("Enabling GUI event loop integration, " "eventloop=%s, matplotlib=%s", gui, backend) if key == "auto": - print ("Using matplotlib backend: %s" % backend) + print(("Using matplotlib backend: %s" % backend)) else: gui = r self.log.info("Enabling GUI event loop integration, " diff --git a/IPython/core/tests/print_argv.py b/IPython/core/tests/print_argv.py index 8d99000..a9acbaa 100644 --- a/IPython/core/tests/print_argv.py +++ b/IPython/core/tests/print_argv.py @@ -1,2 +1,3 @@ +from __future__ import print_function import sys -print sys.argv[1:] +print(sys.argv[1:]) diff --git a/IPython/core/tests/refbug.py b/IPython/core/tests/refbug.py index 5f60abe..69767e2 100644 --- a/IPython/core/tests/refbug.py +++ b/IPython/core/tests/refbug.py @@ -12,6 +12,7 @@ This script is meant to be called by other parts of the test suite that call it via %run as if it were executed interactively by the user. As of 2011-05-29, test_run.py calls it. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Module imports @@ -44,4 +45,4 @@ if __name__ == '__main__': def call_f(): for func in cache: - print 'lowercased:',func().lower() + print('lowercased:',func().lower()) diff --git a/IPython/core/tests/test_debugger.py b/IPython/core/tests/test_debugger.py index 5d1b31f..4f69112 100644 --- a/IPython/core/tests/test_debugger.py +++ b/IPython/core/tests/test_debugger.py @@ -1,5 +1,6 @@ """Tests for debugging machinery. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012, The IPython Development Team. # @@ -36,7 +37,7 @@ class _FakeInput(object): def readline(self): line = next(self.lines) - print line + print(line) return line+'\n' class PdbTestInput(object): diff --git a/IPython/core/tests/test_inputsplitter.py b/IPython/core/tests/test_inputsplitter.py index 9508979..526475b 100644 --- a/IPython/core/tests/test_inputsplitter.py +++ b/IPython/core/tests/test_inputsplitter.py @@ -6,6 +6,7 @@ Authors * Fernando Perez * Robert Kern """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2010-2011 The IPython Development Team # @@ -497,10 +498,10 @@ if __name__ == '__main__': # real interpreter would instead send it for execution somewhere. #src = isp.source; raise EOFError # dbg src, raw = isp.source_raw_reset() - print 'Input source was:\n', src - print 'Raw source was:\n', raw + print('Input source was:\n', src) + print('Raw source was:\n', raw) except EOFError: - print 'Bye' + print('Bye') # Tests for cell magics support diff --git a/IPython/core/ultratb.py b/IPython/core/ultratb.py index 632ae12..8e32fdd 100644 --- a/IPython/core/ultratb.py +++ b/IPython/core/ultratb.py @@ -79,6 +79,7 @@ Inheritance diagram: #***************************************************************************** from __future__ import unicode_literals +from __future__ import print_function import inspect import keyword @@ -1035,7 +1036,7 @@ class VerboseTB(TBTools): try: self.debugger() except KeyboardInterrupt: - print "\nKeyboardInterrupt" + print("\nKeyboardInterrupt") #---------------------------------------------------------------------------- class FormattedTB(VerboseTB, ListTB): @@ -1166,7 +1167,7 @@ class AutoFormattedTB(FormattedTB): try: self.debugger() except KeyboardInterrupt: - print "\nKeyboardInterrupt" + print("\nKeyboardInterrupt") def structured_traceback(self, etype=None, value=None, tb=None, tb_offset=None, context=5): @@ -1240,27 +1241,27 @@ if __name__ == "__main__": i = f - g return h / i - print '' - print '*** Before ***' + print('') + print('*** Before ***') try: - print spam(1, (2, 3)) + print(spam(1, (2, 3))) except: traceback.print_exc() - print '' + print('') handler = ColorTB() - print '*** ColorTB ***' + print('*** ColorTB ***') try: - print spam(1, (2, 3)) + print(spam(1, (2, 3))) except: handler(*sys.exc_info()) - print '' + print('') handler = VerboseTB() - print '*** VerboseTB ***' + print('*** VerboseTB ***') try: - print spam(1, (2, 3)) + print(spam(1, (2, 3))) except: handler(*sys.exc_info()) - print '' + print('') diff --git a/IPython/extensions/rmagic.py b/IPython/extensions/rmagic.py index d95d5e3..c8a330b 100644 --- a/IPython/extensions/rmagic.py +++ b/IPython/extensions/rmagic.py @@ -35,6 +35,7 @@ To enable the magics below, execute ``%load_ext rmagic``. {RGET_DOC} """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2012 The IPython Development Team @@ -617,9 +618,9 @@ class RMagics(Magics): ri.set_writeconsole(old_writeconsole) except RInterpreterError as e: - print(e.stdout) + print((e.stdout)) if not e.stdout.endswith(e.err): - print(e.err) + print((e.err)) rmtree(tmpd) return diff --git a/IPython/extensions/storemagic.py b/IPython/extensions/storemagic.py index 6659783..191ad91 100644 --- a/IPython/extensions/storemagic.py +++ b/IPython/extensions/storemagic.py @@ -9,6 +9,7 @@ To automatically restore stored variables at startup, add this to your c.StoreMagic.autorestore = True """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (c) 2012, The IPython Development Team. # @@ -50,8 +51,8 @@ def refresh_variables(ip): try: obj = db[key] except KeyError: - print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey - print "The error was:", sys.exc_info()[0] + print("Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey) + print("The error was:", sys.exc_info()[0]) else: #print "restored",justkey,"=",obj #dbg ip.user_ns[justkey] = obj @@ -155,7 +156,7 @@ class StoreMagics(Magics): try: obj = db['autorestore/' + arg] except KeyError: - print "no stored variable %s" % arg + print("no stored variable %s" % arg) else: ip.user_ns[arg] = obj else: @@ -170,13 +171,13 @@ class StoreMagics(Magics): else: size = 0 - print 'Stored variables and their in-db values:' + print('Stored variables and their in-db values:') fmt = '%-'+str(size)+'s -> %s' get = db.get for var in vars: justkey = os.path.basename(var) # print 30 first characters from every var - print fmt % (justkey, repr(get(var, ''))[:50]) + print(fmt % (justkey, repr(get(var, ''))[:50])) # default action - store the variable else: @@ -188,8 +189,8 @@ class StoreMagics(Magics): else: fil = open(fnam, 'w') obj = ip.ev(args[0]) - print "Writing '%s' (%s) to file '%s'." % (args[0], - obj.__class__.__name__, fnam) + print("Writing '%s' (%s) to file '%s'." % (args[0], + obj.__class__.__name__, fnam)) if not isinstance (obj, basestring): @@ -217,22 +218,22 @@ class StoreMagics(Magics): staliases = db.get('stored_aliases',{}) staliases[name] = cmd db['stored_aliases'] = staliases - print "Alias stored: %s (%s)" % (name, cmd) + print("Alias stored: %s (%s)" % (name, cmd)) return else: modname = getattr(inspect.getmodule(obj), '__name__', '') if modname == '__main__': - print textwrap.dedent("""\ + print(textwrap.dedent("""\ Warning:%s is %s Proper storage of interactively declared classes (or instances of those classes) is not possible! Only instances of classes in real modules on file system can be %%store'd. - """ % (args[0], obj) ) + """ % (args[0], obj) )) return #pickled = pickle.dumps(obj) db[ 'autorestore/' + args[0] ] = obj - print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__) + print("Stored '%s' (%s)" % (args[0], obj.__class__.__name__)) def load_ipython_extension(ip): diff --git a/IPython/external/decorator/_decorator.py b/IPython/external/decorator/_decorator.py index 2751ab1..e01c5a4 100644 --- a/IPython/external/decorator/_decorator.py +++ b/IPython/external/decorator/_decorator.py @@ -31,6 +31,7 @@ Decorator module, see http://pypi.python.org/pypi/decorator for the documentation. """ +from __future__ import print_function __version__ = '3.3.3' @@ -162,8 +163,8 @@ class FunctionMaker(object): # print >> sys.stderr, 'Compiling %s' % src exec code in evaldict except: - print >> sys.stderr, 'Error in generated code:' - print >> sys.stderr, src + print('Error in generated code:', file=sys.stderr) + print(src, file=sys.stderr) raise func = evaldict[name] if addsource: diff --git a/IPython/external/mathjax.py b/IPython/external/mathjax.py index 24e1e8e..899bdbe 100644 --- a/IPython/external/mathjax.py +++ b/IPython/external/mathjax.py @@ -38,6 +38,7 @@ To find the directory where IPython would like MathJax installed: $ python -m IPython.external.mathjax -d """ +from __future__ import print_function #----------------------------------------------------------------------------- @@ -86,14 +87,14 @@ def prepare_dest(dest, replace=False): if os.path.exists(dest): if replace: - print "removing existing MathJax at %s" % dest + print("removing existing MathJax at %s" % dest) shutil.rmtree(dest) return True else: mathjax_js = os.path.join(dest, 'MathJax.js') if not os.path.exists(mathjax_js): raise IOError("%s exists, but does not contain MathJax.js" % dest) - print "%s already exists" % mathjax_js + print("%s already exists" % mathjax_js) return False else: return True @@ -156,7 +157,7 @@ def install_mathjax(tag='v2.2', dest=default_dest, replace=False, file=None, ext try: anything_to_do = prepare_dest(dest, replace) except OSError as e: - print("ERROR %s, require write access to %s" % (e, dest)) + print(("ERROR %s, require write access to %s" % (e, dest))) return 1 else: if not anything_to_do: @@ -165,11 +166,11 @@ def install_mathjax(tag='v2.2', dest=default_dest, replace=False, file=None, ext if file is None: # download mathjax mathjax_url = "https://github.com/mathjax/MathJax/archive/%s.tar.gz" %tag - print "Downloading mathjax source from %s" % mathjax_url + print("Downloading mathjax source from %s" % mathjax_url) response = urllib2.urlopen(mathjax_url) file = response.fp - print "Extracting to %s" % dest + print("Extracting to %s" % dest) extractor(file, dest) return 0 @@ -205,7 +206,7 @@ def main(): dest = os.path.join(pargs.install_dir, 'mathjax') if pargs.print_dest: - print dest + print(dest) return # remove/replace existing mathjax? diff --git a/IPython/html/notebookapp.py b/IPython/html/notebookapp.py index c1f1a77..002f984 100644 --- a/IPython/html/notebookapp.py +++ b/IPython/html/notebookapp.py @@ -5,6 +5,7 @@ Authors: * Brian Granger """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2013 The IPython Development Team # @@ -628,7 +629,7 @@ class NotebookApp(BaseIPythonApplication): time.sleep(0.1) info = self.log.info info('interrupted') - print self.notebook_info() + print(self.notebook_info()) sys.stdout.write("Shutdown this notebook server (y/[n])? ") sys.stdout.flush() r,w,x = select.select([sys.stdin], [], [], 5) @@ -639,8 +640,8 @@ class NotebookApp(BaseIPythonApplication): ioloop.IOLoop.instance().stop() return else: - print "No answer for 5s:", - print "resuming operation..." + print("No answer for 5s:", end=' ') + print("resuming operation...") # no answer, or answer is no: # set it back to original SIGINT handler # use IOLoop.add_callback because signal.signal must be called @@ -652,7 +653,7 @@ class NotebookApp(BaseIPythonApplication): ioloop.IOLoop.instance().stop() def _signal_info(self, sig, frame): - print self.notebook_info() + print(self.notebook_info()) def init_components(self): """Check the components submodule, and warn if it's unclean""" diff --git a/IPython/html/services/notebooks/tests/test_nbmanager.py b/IPython/html/services/notebooks/tests/test_nbmanager.py index 2aeb276..2135882 100644 --- a/IPython/html/services/notebooks/tests/test_nbmanager.py +++ b/IPython/html/services/notebooks/tests/test_nbmanager.py @@ -1,5 +1,6 @@ # coding: utf-8 """Tests for the notebook manager.""" +from __future__ import print_function import os @@ -66,7 +67,7 @@ class TestNotebookManager(TestCase): try: os.makedirs(os_path) except OSError: - print "Directory already exists." + print("Directory already exists.") def test_create_notebook_model(self): with TemporaryDirectory() as td: diff --git a/IPython/lib/backgroundjobs.py b/IPython/lib/backgroundjobs.py index 839d6ca..03959b0 100644 --- a/IPython/lib/backgroundjobs.py +++ b/IPython/lib/backgroundjobs.py @@ -21,6 +21,7 @@ separate implementation). An example notebook is provided in our documentation illustrating interactive use of the system. """ +from __future__ import print_function #***************************************************************************** # Copyright (C) 2005-2006 Fernando Perez @@ -190,7 +191,7 @@ class BackgroundJobManager(object): job.num = len(self.all)+1 if self.all else 0 self.running.append(job) self.all[job.num] = job - print 'Starting job # %s in a separate thread.' % job.num + print('Starting job # %s in a separate thread.' % job.num) job.start() return job @@ -245,10 +246,10 @@ class BackgroundJobManager(object): Return True if the group had any elements.""" if group: - print '%s jobs:' % name + print('%s jobs:' % name) for job in group: - print '%s : %s' % (job.num,job) - print + print('%s : %s' % (job.num,job)) + print() return True def _group_flush(self,group,name): @@ -259,7 +260,7 @@ class BackgroundJobManager(object): njobs = len(group) if njobs: plural = {1:''}.setdefault(njobs,'s') - print 'Flushing %s %s job%s.' % (njobs,name,plural) + print('Flushing %s %s job%s.' % (njobs,name,plural)) group[:] = [] return True @@ -325,7 +326,7 @@ class BackgroundJobManager(object): fl_comp = self._group_flush(self.completed, 'Completed') fl_dead = self._group_flush(self.dead, 'Dead') if not (fl_comp or fl_dead): - print 'No jobs to flush.' + print('No jobs to flush.') def result(self,num): """result(N) -> return the result of job N.""" @@ -345,9 +346,9 @@ class BackgroundJobManager(object): if job is None: self._update_status() for deadjob in self.dead: - print "Traceback for: %r" % deadjob + print("Traceback for: %r" % deadjob) self._traceback(deadjob) - print + print() else: self._traceback(job) @@ -416,7 +417,7 @@ class BackgroundJobBase(threading.Thread): return '' % (self.num, self.strform) def traceback(self): - print self._tb + print(self._tb) def run(self): try: diff --git a/IPython/lib/deepreload.py b/IPython/lib/deepreload.py index 4410696..4197166 100644 --- a/IPython/lib/deepreload.py +++ b/IPython/lib/deepreload.py @@ -17,6 +17,7 @@ Alternatively, you can add a dreload builtin alongside normal reload with:: This code is almost entirely based on knee.py, which is a Python re-implementation of hierarchical module import. """ +from __future__ import print_function #***************************************************************************** # Copyright (C) 2001 Nathaniel Gray # @@ -167,7 +168,7 @@ def import_submodule(mod, subname, fullname): if fullname in found_now and fullname in sys.modules: m = sys.modules[fullname] else: - print 'Reloading', fullname + print('Reloading', fullname) found_now[fullname] = 1 oldm = sys.modules.get(fullname, None) diff --git a/IPython/lib/editorhooks.py b/IPython/lib/editorhooks.py index 593900e..7f98a6a 100644 --- a/IPython/lib/editorhooks.py +++ b/IPython/lib/editorhooks.py @@ -4,6 +4,7 @@ They should honor the line number argument, at least. Contributions are *very* welcome. """ +from __future__ import print_function import os import pipes @@ -45,7 +46,7 @@ def install_editor(template, wait=False): if line is None: line = 0 cmd = template.format(filename=pipes.quote(filename), line=line) - print ">", cmd + print(">", cmd) proc = subprocess.Popen(cmd, shell=True) if wait and proc.wait() != 0: raise TryNext() diff --git a/IPython/lib/inputhookglut.py b/IPython/lib/inputhookglut.py index ae5c42e..14bafe1 100644 --- a/IPython/lib/inputhookglut.py +++ b/IPython/lib/inputhookglut.py @@ -2,6 +2,7 @@ """ GLUT Inputhook support functions """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team @@ -114,7 +115,7 @@ def glut_close(): def glut_int_handler(signum, frame): # Catch sigint and print the defautl message signal.signal(signal.SIGINT, signal.default_int_handler) - print '\nKeyboardInterrupt' + print('\nKeyboardInterrupt') # Need to reprint the prompt at this stage diff --git a/IPython/lib/pretty.py b/IPython/lib/pretty.py index fbc830b..e4bb727 100644 --- a/IPython/lib/pretty.py +++ b/IPython/lib/pretty.py @@ -103,6 +103,7 @@ Inheritance diagram: Portions (c) 2009 by Robert Kern. :license: BSD License. """ +from __future__ import print_function from contextlib import contextmanager import sys import types @@ -784,6 +785,6 @@ if __name__ == '__main__': self.list = ["blub", "blah", self] def get_foo(self): - print "foo" + print("foo") pprint(Foo(), verbose=True) diff --git a/IPython/nbconvert/postprocessors/serve.py b/IPython/nbconvert/postprocessors/serve.py index 373b168..7751372 100644 --- a/IPython/nbconvert/postprocessors/serve.py +++ b/IPython/nbconvert/postprocessors/serve.py @@ -1,4 +1,5 @@ """PostProcessor for serving reveal.js HTML slideshows.""" +from __future__ import print_function #----------------------------------------------------------------------------- #Copyright (c) 2013, the IPython Development Team. # @@ -92,7 +93,7 @@ class ServePostProcessor(PostProcessorBase): http_server = httpserver.HTTPServer(app) http_server.listen(self.port, address=self.ip) url = "http://%s:%i/%s" % (self.ip, self.port, filename) - print("Serving your slides at %s" % url) + print(("Serving your slides at %s" % url)) print("Use Control-C to stop this server") if self.open_in_browser: webbrowser.open(url, new=2) diff --git a/IPython/nbconvert/writers/debug.py b/IPython/nbconvert/writers/debug.py index 5c5ea43..88aa105 100644 --- a/IPython/nbconvert/writers/debug.py +++ b/IPython/nbconvert/writers/debug.py @@ -1,6 +1,7 @@ """ Contains debug writer. """ +from __future__ import print_function #----------------------------------------------------------------------------- #Copyright (c) 2013, the IPython Development Team. # @@ -34,9 +35,9 @@ class DebugWriter(WriterBase): """ if isinstance(resources['outputs'], dict): - print("outputs extracted from %s" % notebook_name) - print('-' * 80) + print(("outputs extracted from %s" % notebook_name)) + print(('-' * 80)) pprint(resources['outputs'], indent=2, width=70) else: - print("no outputs extracted from %s" % notebook_name) - print('=' * 80) + print(("no outputs extracted from %s" % notebook_name)) + print(('=' * 80)) diff --git a/IPython/nbformat/v3/validator.py b/IPython/nbformat/v3/validator.py index 3bbca3b..5de2202 100755 --- a/IPython/nbformat/v3/validator.py +++ b/IPython/nbformat/v3/validator.py @@ -1,3 +1,4 @@ +from __future__ import print_function #!/usr/bin/env python # -*- coding: utf8 -*- import argparse @@ -79,10 +80,10 @@ if __name__ == '__main__': key=args.key, verbose=args.verbose) if nerror is 0: - print u"[Pass]",name + print(u"[Pass]",name) else : - print u"[ ]",name,'(%d)'%(nerror) + print(u"[ ]",name,'(%d)'%(nerror)) if args.verbose : - print '==================================================' + print('==================================================') diff --git a/IPython/parallel/apps/ipclusterapp.py b/IPython/parallel/apps/ipclusterapp.py index 8d07ae2..f93122c 100755 --- a/IPython/parallel/apps/ipclusterapp.py +++ b/IPython/parallel/apps/ipclusterapp.py @@ -9,6 +9,7 @@ Authors: * MinRK """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team @@ -595,8 +596,8 @@ class IPClusterApp(BaseIPythonApplication): def start(self): if self.subapp is None: - print "No subcommand specified. Must specify one of: %s"%(self.subcommands.keys()) - print + print("No subcommand specified. Must specify one of: %s"%(self.subcommands.keys())) + print() self.print_description() self.print_subcommands() self.exit(1) diff --git a/IPython/parallel/client/client.py b/IPython/parallel/client/client.py index 0b0c722..7fb72cd 100644 --- a/IPython/parallel/client/client.py +++ b/IPython/parallel/client/client.py @@ -4,6 +4,7 @@ Authors: * MinRK """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2010-2011 The IPython Development Team # @@ -738,9 +739,9 @@ class Client(HasTraits): msg_id = parent['msg_id'] if msg_id not in self.outstanding: if msg_id in self.history: - print ("got stale result: %s"%msg_id) + print(("got stale result: %s"%msg_id)) else: - print ("got unknown result: %s"%msg_id) + print(("got unknown result: %s"%msg_id)) else: self.outstanding.remove(msg_id) @@ -774,11 +775,11 @@ class Client(HasTraits): msg_id = parent['msg_id'] if msg_id not in self.outstanding: if msg_id in self.history: - print ("got stale result: %s"%msg_id) - print self.results[msg_id] - print msg + print(("got stale result: %s"%msg_id)) + print(self.results[msg_id]) + print(msg) else: - print ("got unknown result: %s"%msg_id) + print(("got unknown result: %s"%msg_id)) else: self.outstanding.remove(msg_id) content = msg['content'] diff --git a/IPython/parallel/client/magics.py b/IPython/parallel/client/magics.py index 537e1fe..b74403b 100644 --- a/IPython/parallel/client/magics.py +++ b/IPython/parallel/client/magics.py @@ -26,6 +26,7 @@ Usage {CONFIG_DOC} """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2008 The IPython Development Team @@ -251,7 +252,7 @@ class ParallelMagics(Magics): else: str_targets = str(targets) if self.verbose: - print base + " execution on engine(s): %s" % str_targets + print(base + " execution on engine(s): %s" % str_targets) result = self.view.execute(cell, silent=False, block=False) self.last_result = result @@ -358,7 +359,7 @@ class ParallelMagics(Magics): self.shell.run_cell = self.pxrun_cell self._autopx = True - print "%autopx enabled" + print("%autopx enabled") def _disable_autopx(self): """Disable %autopx by restoring the original InteractiveShell.run_cell. @@ -366,7 +367,7 @@ class ParallelMagics(Magics): if self._autopx: self.shell.run_cell = self._original_run_cell self._autopx = False - print "%autopx disabled" + print("%autopx disabled") def pxrun_cell(self, raw_cell, store_history=False, silent=False): """drop-in replacement for InteractiveShell.run_cell. diff --git a/IPython/parallel/client/view.py b/IPython/parallel/client/view.py index 7bd4326..aa8a007 100644 --- a/IPython/parallel/client/view.py +++ b/IPython/parallel/client/view.py @@ -4,6 +4,7 @@ Authors: * Min RK """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2010-2011 The IPython Development Team # @@ -482,9 +483,9 @@ class DirectView(View): modules.add(key) if not quiet: if fromlist: - print "importing %s from %s on engine(s)"%(','.join(fromlist), name) + print("importing %s from %s on engine(s)"%(','.join(fromlist), name)) else: - print "importing %s on engine(s)"%name + print("importing %s on engine(s)"%name) results.append(self.apply_async(remote_import, name, fromlist, level)) # restore override __builtin__.__import__ = save_import @@ -830,7 +831,7 @@ class DirectView(View): # This is injected into __builtins__. ip = get_ipython() except NameError: - print "The IPython parallel magics (%px, etc.) only work within IPython." + print("The IPython parallel magics (%px, etc.) only work within IPython.") return M = ParallelMagics(ip, self, suffix) diff --git a/IPython/parallel/tests/__init__.py b/IPython/parallel/tests/__init__.py index 8c8c7db..367ae7b 100644 --- a/IPython/parallel/tests/__init__.py +++ b/IPython/parallel/tests/__init__.py @@ -1,4 +1,5 @@ """toplevel setup/teardown for parallel tests.""" +from __future__ import print_function #------------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team @@ -118,15 +119,15 @@ def teardown(): try: p.stop() except Exception as e: - print e + print(e) pass if p.poll() is None: time.sleep(.25) if p.poll() is None: try: - print 'cleaning up test process...' + print('cleaning up test process...') p.signal(SIGKILL) except: - print "couldn't shutdown process: ", p + print("couldn't shutdown process: ", p) blackhole.close() diff --git a/IPython/sphinxext/ipython_directive.py b/IPython/sphinxext/ipython_directive.py index 4ab090e..9942e5e 100644 --- a/IPython/sphinxext/ipython_directive.py +++ b/IPython/sphinxext/ipython_directive.py @@ -51,6 +51,7 @@ Authors - VáclavŠmilauer : Prompt generalizations. - Skipper Seabold, refactoring, cleanups, pure python addition """ +from __future__ import print_function #----------------------------------------------------------------------------- # Imports @@ -649,7 +650,7 @@ class IPythonDirective(Directive): #print lines if len(lines)>2: if debug: - print '\n'.join(lines) + print('\n'.join(lines)) else: #NOTE: this raises some errors, what's it for? #print 'INSERTING %d lines'%len(lines) self.state_machine.insert_input( @@ -826,4 +827,4 @@ if __name__=='__main__': if not os.path.isdir('_static'): os.mkdir('_static') test() - print 'All OK? Check figures in _static/' + print('All OK? Check figures in _static/') diff --git a/IPython/terminal/embed.py b/IPython/terminal/embed.py index d343955..33f9d33 100644 --- a/IPython/terminal/embed.py +++ b/IPython/terminal/embed.py @@ -23,6 +23,7 @@ Notes #----------------------------------------------------------------------------- from __future__ import with_statement +from __future__ import print_function import sys import warnings @@ -154,7 +155,7 @@ class InteractiveShellEmbed(TerminalInteractiveShell): self.banner2 = self.old_banner2 if self.exit_msg is not None: - print self.exit_msg + print(self.exit_msg) def mainloop(self, local_ns=None, module=None, stack_depth=0, display_banner=None, global_ns=None, compile_flags=None): diff --git a/IPython/terminal/ipapp.py b/IPython/terminal/ipapp.py index 3a0c314..f9dd677 100755 --- a/IPython/terminal/ipapp.py +++ b/IPython/terminal/ipapp.py @@ -24,6 +24,7 @@ Authors #----------------------------------------------------------------------------- from __future__ import absolute_import +from __future__ import print_function import logging import os @@ -196,7 +197,7 @@ class LocateIPythonApp(BaseIPythonApplication): if self.subapp is not None: return self.subapp.start() else: - print self.ipython_dir + print(self.ipython_dir) class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): @@ -344,7 +345,7 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): if self.display_banner and self.interact: self.shell.show_banner() # Make sure there is a space below the banner. - if self.log_level <= logging.INFO: print + if self.log_level <= logging.INFO: print() def _pylab_changed(self, name, old, new): """Replace --pylab='inline' with --pylab='auto'""" diff --git a/IPython/testing/plugin/iptest.py b/IPython/testing/plugin/iptest.py index 3a93d91..a75cab9 100755 --- a/IPython/testing/plugin/iptest.py +++ b/IPython/testing/plugin/iptest.py @@ -1,6 +1,7 @@ #!/usr/bin/env python """Nose-based test runner. """ +from __future__ import print_function from nose.core import main from nose.plugins.builtin import plugins @@ -10,8 +11,8 @@ from . import ipdoctest from .ipdoctest import IPDocTestRunner if __name__ == '__main__': - print 'WARNING: this code is incomplete!' - print + print('WARNING: this code is incomplete!') + print() pp = [x() for x in plugins] # activate all builtin plugins first main(testRunner=IPDocTestRunner(), diff --git a/IPython/testing/plugin/show_refs.py b/IPython/testing/plugin/show_refs.py index d829644..9cdea1a 100644 --- a/IPython/testing/plugin/show_refs.py +++ b/IPython/testing/plugin/show_refs.py @@ -2,6 +2,7 @@ This is used by a companion test case. """ +from __future__ import print_function import gc @@ -16,4 +17,4 @@ if __name__ == '__main__': c_refs = gc.get_referrers(c) ref_ids = map(id,c_refs) - print 'c referrers:',map(type,c_refs) + print('c referrers:',map(type,c_refs)) diff --git a/IPython/testing/plugin/simplevars.py b/IPython/testing/plugin/simplevars.py index b9286c7..5134c6e 100644 --- a/IPython/testing/plugin/simplevars.py +++ b/IPython/testing/plugin/simplevars.py @@ -1,2 +1,3 @@ +from __future__ import print_function x = 1 -print 'x is:',x +print('x is:',x) diff --git a/IPython/testing/tests/test_decorators.py b/IPython/testing/tests/test_decorators.py index 340c00a..77d7203 100644 --- a/IPython/testing/tests/test_decorators.py +++ b/IPython/testing/tests/test_decorators.py @@ -1,5 +1,6 @@ """Tests for the decorators we've created for IPython. """ +from __future__ import print_function # Module imports # Std lib @@ -67,9 +68,9 @@ def doctest_bad(x,y=1,**k): >>> 1+1 3 """ - print 'x:',x - print 'y:',y - print 'k:',k + print('x:',x) + print('y:',y) + print('k:',k) def call_doctest_bad(): @@ -117,7 +118,7 @@ class FooClass(object): >>> f = FooClass(3) junk """ - print 'Making a FooClass.' + print('Making a FooClass.') self.x = x @skip_doctest diff --git a/IPython/testing/tests/test_tools.py b/IPython/testing/tests/test_tools.py index 36a38d7..a4c2e77 100644 --- a/IPython/testing/tests/test_tools.py +++ b/IPython/testing/tests/test_tools.py @@ -14,6 +14,7 @@ Tests for testing.tools # Imports #----------------------------------------------------------------------------- from __future__ import with_statement +from __future__ import print_function import os import unittest @@ -73,16 +74,16 @@ def test_temp_pyfile(): class TestAssertPrints(unittest.TestCase): def test_passing(self): with tt.AssertPrints("abc"): - print "abcd" - print "def" - print b"ghi" + print("abcd") + print("def") + print(b"ghi") def test_failing(self): def func(): with tt.AssertPrints("abc"): - print "acd" - print "def" - print b"ghi" + print("acd") + print("def") + print(b"ghi") self.assertRaises(AssertionError, func) diff --git a/IPython/utils/_tokenize_py2.py b/IPython/utils/_tokenize_py2.py index 16a3c9d..fcce39c 100644 --- a/IPython/utils/_tokenize_py2.py +++ b/IPython/utils/_tokenize_py2.py @@ -31,6 +31,7 @@ Older entry points are the same, except instead of generating tokens, tokeneater is a callback function to which the 5 fields described above are passed as 5 arguments, each time a new token is found.""" +from __future__ import print_function __author__ = 'Ka-Ping Yee ' __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, ' @@ -161,8 +162,8 @@ class StopTokenizing(Exception): pass def printtoken(type, token, srow_scol, erow_ecol, line): # for testing srow, scol = srow_scol erow, ecol = erow_ecol - print "%d,%d-%d,%d:\t%s\t%s" % \ - (srow, scol, erow, ecol, tok_name[type], repr(token)) + print("%d,%d-%d,%d:\t%s\t%s" % \ + (srow, scol, erow, ecol, tok_name[type], repr(token))) def tokenize(readline, tokeneater=printtoken): """ diff --git a/IPython/utils/frame.py b/IPython/utils/frame.py index 07cc553..ff2bfab 100644 --- a/IPython/utils/frame.py +++ b/IPython/utils/frame.py @@ -2,6 +2,7 @@ """ Utilities for working with stack frames. """ +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team @@ -78,8 +79,8 @@ def debugx(expr,pre_msg=''): expr->value pair.""" cf = sys._getframe(1) - print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, - eval(expr,cf.f_globals,cf.f_locals)) + print('[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, + eval(expr,cf.f_globals,cf.f_locals))) # deactivate it by uncommenting the following line, which makes it a no-op diff --git a/IPython/utils/pickleshare.py b/IPython/utils/pickleshare.py index 0d4a443..9c890da 100755 --- a/IPython/utils/pickleshare.py +++ b/IPython/utils/pickleshare.py @@ -32,6 +32,7 @@ Author: Ville Vainio License: MIT open source license. """ +from __future__ import print_function from IPython.external.path import path as Path import os,stat,time @@ -138,7 +139,7 @@ class PickleShareDB(collections.MutableMapping): try: all.update(self[f]) except KeyError: - print "Corrupt",f,"deleted - hset is not threadsafe!" + print("Corrupt",f,"deleted - hset is not threadsafe!") del self[f] self.uncache(f) @@ -280,25 +281,25 @@ class PickleShareLink: def test(): db = PickleShareDB('~/testpickleshare') db.clear() - print "Should be empty:",db.items() + print("Should be empty:",db.items()) db['hello'] = 15 db['aku ankka'] = [1,2,313] db['paths/nest/ok/keyname'] = [1,(5,46)] db.hset('hash', 'aku', 12) db.hset('hash', 'ankka', 313) - print "12 =",db.hget('hash','aku') - print "313 =",db.hget('hash','ankka') - print "all hashed",db.hdict('hash') - print db.keys() - print db.keys('paths/nest/ok/k*') - print dict(db) # snapsot of whole db + print("12 =",db.hget('hash','aku')) + print("313 =",db.hget('hash','ankka')) + print("all hashed",db.hdict('hash')) + print(db.keys()) + print(db.keys('paths/nest/ok/k*')) + print(dict(db)) # snapsot of whole db db.uncache() # frees memory, causes re-reads later # shorthand for accessing deeply nested files lnk = db.getlink('myobjects/test') lnk.foo = 2 lnk.bar = lnk.foo + 5 - print lnk.bar # 7 + print(lnk.bar) # 7 def stress(): db = PickleShareDB('~/fsdbtest') @@ -316,7 +317,7 @@ def stress(): db[str(j)] = db.get(str(j), []) + [(i,j,"proc %d" % os.getpid())] db.hset('hash',j, db.hget('hash',j,15) + 1 ) - print i, + print(i, end=' ') sys.stdout.flush() if i % 10 == 0: db.uncache() @@ -335,7 +336,7 @@ def main(): DB = PickleShareDB import sys if len(sys.argv) < 2: - print usage + print(usage) return cmd = sys.argv[1] @@ -355,7 +356,7 @@ def main(): elif cmd == 'testwait': db = DB(args[0]) db.clear() - print db.waitget('250') + print(db.waitget('250')) elif cmd == 'test': test() stress() diff --git a/IPython/utils/tests/test_text.py b/IPython/utils/tests/test_text.py index 5803a85..5a9eb21 100644 --- a/IPython/utils/tests/test_text.py +++ b/IPython/utils/tests/test_text.py @@ -1,5 +1,6 @@ # encoding: utf-8 """Tests for IPython.utils.text""" +from __future__ import print_function #----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team @@ -45,11 +46,11 @@ def test_columnize_random(): longer_line = max([len(x) for x in out.split('\n')]) longer_element = max(rand_len) if longer_line > displaywidth: - print "Columnize displayed something lager than displaywidth : %s " % longer_line - print "longer element : %s " % longer_element - print "displaywidth : %s " % displaywidth - print "number of element : %s " % nitems - print "size of each element :\n %s" % rand_len + print("Columnize displayed something lager than displaywidth : %s " % longer_line) + print("longer element : %s " % longer_element) + print("displaywidth : %s " % displaywidth) + print("number of element : %s " % nitems) + print("size of each element :\n %s" % rand_len) assert False def test_columnize_medium():