Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

py3k print: WIP... overzealous fixing, breaks py2k

  • Loading branch information...
commit 59e98c264e7848b8e2f83b3c507f87e4ffb2d578 1 parent 1981689
@bfroehle authored
Showing with 446 additions and 446 deletions.
  1. +21 −21 IPython/config/application.py
  2. +1 −1  IPython/config/configurable.py
  3. +12 −12 IPython/core/logger.py
  4. +2 −2 IPython/core/magic.py
  5. +2 −2 IPython/core/magics/auto.py
  6. +11 −11 IPython/core/magics/code.py
  7. +3 −3 IPython/core/magics/config.py
  8. +4 −4 IPython/core/magics/deprecated.py
  9. +29 −29 IPython/core/magics/execution.py
  10. +3 −3 IPython/core/magics/extension.py
  11. +29 −29 IPython/core/magics/namespace.py
  12. +16 −16 IPython/core/magics/osm.py
  13. +6 −6 IPython/core/magics/script.py
  14. +18 −18 IPython/core/profileapp.py
  15. +5 −5 IPython/core/pylabtools.py
  16. +1 −1  IPython/core/tests/refbug.py
  17. +1 −1  IPython/core/tests/test_debugger.py
  18. +3 −3 IPython/core/tests/test_inputsplitter.py
  19. +12 −12 IPython/core/ultratb.py
  20. +5 −5 IPython/deathrow/Gnuplot2.py
  21. +1 −1  IPython/deathrow/GnuplotInteractive.py
  22. +1 −1  IPython/deathrow/GnuplotRuntime.py
  23. +1 −1  IPython/deathrow/PhysicalQInput.py
  24. +1 −1  IPython/deathrow/dtutils.py
  25. +2 −2 IPython/deathrow/gui/wx/ipshell_nonblocking.py
  26. +2 −2 IPython/deathrow/gui/wx/wxIPython.py
  27. +1 −1  IPython/deathrow/ipipe.py
  28. +4 −4 IPython/deathrow/ipy_kitcfg.py
  29. +1 −1  IPython/deathrow/ipy_profile_numpy.py
  30. +1 −1  IPython/deathrow/ipy_profile_scipy.py
  31. +2 −2 IPython/deathrow/ipy_profile_sh.py
  32. +12 −12 IPython/deathrow/ipy_profile_zope.py
  33. +1 −1  IPython/deathrow/ipy_traits_completer.py
  34. +5 −5 IPython/deathrow/numeric_formats.py
  35. +2 −2 IPython/deathrow/oldfrontend/cocoa/cocoa_frontend.py
  36. +5 −5 IPython/deathrow/oldfrontend/linefrontendbase.py
  37. +1 −1  IPython/deathrow/oldfrontend/prefilterfrontend.py
  38. +6 −6 IPython/deathrow/oldfrontend/wx/wx_frontend.py
  39. +20 −20 IPython/deathrow/outputtrap.py
  40. +4 −4 IPython/deathrow/tests/test_prefilter.py
  41. +8 −8 IPython/deathrow/twshell.py
  42. +10 −10 IPython/extensions/storemagic.py
  43. +2 −2 IPython/external/decorator/_decorator.py
  44. +5 −5 IPython/external/mathjax.py
  45. +1 −1  IPython/frontend/html/notebook/handlers.py
  46. +2 −2 IPython/frontend/html/notebook/notebookapp.py
  47. +1 −1  IPython/frontend/terminal/embed.py
  48. +2 −2 IPython/frontend/terminal/ipapp.py
  49. +9 −9 IPython/lib/backgroundjobs.py
  50. +1 −1  IPython/lib/deepreload.py
  51. +1 −1  IPython/lib/inputhookglut.py
  52. +1 −1  IPython/lib/pretty.py
  53. +2 −2 IPython/parallel/apps/ipclusterapp.py
  54. +6 −6 IPython/parallel/client/client.py
  55. +3 −3 IPython/parallel/client/magics.py
  56. +1 −1  IPython/parallel/client/map.py
  57. +3 −3 IPython/parallel/client/view.py
  58. +4 −4 IPython/parallel/tests/__init__.py
  59. +4 −4 IPython/quarantine/envpersist.py
  60. +1 −1  IPython/quarantine/ipy_editors.py
  61. +1 −1  IPython/quarantine/ipy_exportdb.py
  62. +3 −3 IPython/quarantine/ipy_extutil.py
  63. +6 −6 IPython/quarantine/ipy_fsops.py
  64. +1 −1  IPython/quarantine/ipy_gnuglobal.py
  65. +35 −35 IPython/quarantine/ipy_jot.py
  66. +2 −2 IPython/quarantine/ipy_lookfor.py
  67. +2 −2 IPython/quarantine/ipy_rehashdir.py
  68. +1 −1  IPython/quarantine/ipy_server.py
  69. +2 −2 IPython/quarantine/ipy_signals.py
  70. +1 −1  IPython/quarantine/ipy_synchronize_with.py
  71. +5 −5 IPython/quarantine/ipy_which.py
  72. +7 −7 IPython/quarantine/ipy_winpdb.py
  73. +3 −3 IPython/quarantine/ipy_workdir.py
  74. +7 −7 IPython/quarantine/jobctrl.py
  75. +7 −7 IPython/quarantine/ledit.py
  76. +2 −2 IPython/quarantine/win32clip.py
  77. +2 −2 IPython/testing/plugin/iptest.py
  78. +1 −1  IPython/testing/plugin/show_refs.py
  79. +1 −1  IPython/testing/plugin/simplevars.py
  80. +4 −4 IPython/testing/tests/test_decorators.py
  81. +6 −6 IPython/testing/tests/test_tools.py
  82. +2 −2 IPython/utils/frame.py
  83. +12 −12 IPython/utils/pickleshare.py
  84. +5 −5 IPython/utils/tests/test_text.py
  85. +4 −4 IPython/utils/upgradedir.py
View
42 IPython/config/application.py
@@ -239,7 +239,7 @@ def print_alias_help(self):
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."""
@@ -252,7 +252,7 @@ def print_flag_help(self):
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:
@@ -263,10 +263,10 @@ def print_options(self):
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."""
@@ -284,7 +284,7 @@ def print_subcommands(self):
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.
@@ -296,25 +296,25 @@ def print_help(self, classes=False):
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()
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.
@@ -323,15 +323,15 @@ def print_examples(self):
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."""
View
2  IPython/config/configurable.py
@@ -200,7 +200,7 @@ def class_get_trait_help(cls, trait, inst=None):
@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):
View
24 IPython/core/logger.py
@@ -137,33 +137,33 @@ def switch_log(self,val):
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 +213,7 @@ def logstop(self):
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.
View
4 IPython/core/magic.py
@@ -540,8 +540,8 @@ def __init__(self, shell):
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."""
View
4 IPython/core/magics/auto.py
@@ -57,7 +57,7 @@ def automagic(self, parameter_s=''):
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 +125,4 @@ def autocall(self, parameter_s=''):
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])
View
22 IPython/core/magics/code.py
@@ -88,15 +88,15 @@ def save(self, parameter_s=''):
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:
@@ -106,8 +106,8 @@ def save(self, parameter_s=''):
# 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=''):
@@ -129,7 +129,7 @@ def pastebin(self, parameter_s=''):
try:
code = self.shell.find_user_code(args)
except (ValueError, TypeError) as e:
- print e.args[0]
+ print(e.args[0])
return
post_data = json.dumps({
@@ -198,7 +198,7 @@ def load(self, arg_s):
ans = True
if ans is False :
- print 'Operation cancelled.'
+ print('Operation cancelled.')
return
self.shell.set_next_input(contents)
@@ -323,7 +323,7 @@ class DataIsObject(Exception): pass
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)
return filename, lineno, use_temp
@@ -493,7 +493,7 @@ def edit(self, parameter_s='',last_call=['','']):
return
# do actual editing here
- print 'Editing...',
+ print('Editing...', end=' ')
sys.stdout.flush()
try:
# Quote filenames that may have spaces in them
@@ -510,9 +510,9 @@ def edit(self, parameter_s='',last_call=['','']):
self.shell.user_ns['pasted_block'] = file_read(filename)
if 'x' in opts: # -x prevents actual execution
- print
+ print()
else:
- print 'done. Executing edited code...'
+ print('done. Executing edited code...')
if 'r' in opts: # Untranslated IPython code
self.shell.run_cell(file_read(filename),
store_history=False)
View
6 IPython/core/magics/config.py
@@ -115,9 +115,9 @@ def config(self, s):
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
@@ -127,7 +127,7 @@ def config(self, s):
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 '=' not in line:
raise UsageError("Invalid config statement: %r, "
View
8 IPython/core/magics/deprecated.py
@@ -26,20 +26,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 <name>`",
"or `ipython --profile=<name>` 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 <name>` to initialize a profile",
"with the default config files.",
"Add `--reset` to overwrite already existing config files with defaults."
- ])
+ ]))
View
58 IPython/core/magics/execution.py
@@ -238,22 +238,22 @@ def prun(self, parameter_s='', cell=None, user_mode=True,
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
@@ -293,7 +293,7 @@ def pdb(self, parameter_s=''):
# 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))
@line_magic
def debug(self, parameter_s=''):
@@ -455,7 +455,7 @@ def run(self, parameter_s='', runner=None,
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:
@@ -550,8 +550,8 @@ def run(self, parameter_s='', runner=None,
# if we find a good linenumber, set the breakpoint
deb.do_break('%s:%s' % (filename, bp))
# Start file run
- print "NOTE: Enter 'c' at the",
- print "%s prompt to start your script." % deb.prompt
+ print("NOTE: Enter 'c' at the", end=' ')
+ print("%s prompt to start your script." % deb.prompt)
ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
try:
#save filename so it can be used by methods on the deb object
@@ -586,9 +586,9 @@ def run(self, parameter_s='', runner=None,
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()
@@ -598,13 +598,13 @@ def run(self, parameter_s='', runner=None,
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 : %10.2f %10.2f" % ('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 : %10.2f %10.2f" % ('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))
else:
# regular execution
@@ -804,12 +804,12 @@ def timeit(self, line='', cell=None):
order = 0
else:
order = 3
- print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
+ print(u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
precision,
best * scaling[order],
- units[order])
+ units[order]))
if tc > tc_min:
- print "Compiler time: %.2f s" % tc
+ print("Compiler time: %.2f s" % tc)
@skip_doctest
@needs_local_scope
@@ -899,11 +899,11 @@ def time(self,parameter_s, local_ns=None):
cpu_user = end[0]-st[0]
cpu_sys = end[1]-st[1]
cpu_tot = cpu_user+cpu_sys
- print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
- (cpu_user,cpu_sys,cpu_tot)
- print "Wall time: %.2f s" % wall_time
+ print("CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
+ (cpu_user,cpu_sys,cpu_tot))
+ print("Wall time: %.2f s" % wall_time)
if tc > tc_min:
- print "Compiler : %.2f s" % tc
+ print("Compiler : %.2f s" % tc)
return out
@skip_doctest
@@ -977,13 +977,13 @@ def macro(self, parameter_s=''):
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)
- 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='?',
View
6 IPython/core/magics/extension.py
@@ -46,12 +46,12 @@ def install_ext(self, parameter_s=''):
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
View
58 IPython/core/magics/namespace.py
@@ -117,7 +117,7 @@ def pfile(self, parameter_s=''):
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 +204,7 @@ def psearch(self, parameter_s=''):
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
@@ -326,20 +326,20 @@ def who(self, parameter_s=''):
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
@@ -377,9 +377,9 @@ def whos(self, parameter_s=''):
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...
@@ -431,15 +431,15 @@ def type_name(v):
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:
@@ -449,13 +449,13 @@ def type_name(v):
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)
@@ -466,9 +466,9 @@ def type_name(v):
vstr = "<object with id %d (str() failed)>" % 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=''):
@@ -539,7 +539,7 @@ def reset(self, parameter_s=''):
except StdinNotImplementedError:
ans = True
if not ans:
- print 'Nothing done.'
+ print('Nothing done.')
return
if 's' in opts: # Soft reset
@@ -556,11 +556,11 @@ def reset(self, parameter_s=''):
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)
@@ -584,15 +584,15 @@ def reset(self, parameter_s=''):
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()
@@ -669,11 +669,11 @@ def reset_selective(self, parameter_s=''):
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:
@@ -700,4 +700,4 @@ def xdel(self, parameter_s=''):
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))
View
32 IPython/core/magics/osm.py
@@ -106,7 +106,7 @@ def alias(self, parameter_s=''):
# 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
@@ -114,7 +114,7 @@ def alias(self, parameter_s=''):
try:
alias,cmd = par.split(None, 1)
except:
- print oinspect.getdoc(self.alias)
+ print(oinspect.getdoc(self.alias))
else:
self.shell.alias_manager.soft_define_alias(alias, cmd)
# end magic_alias
@@ -127,7 +127,7 @@ def unalias(self, parameter_s=''):
self.shell.alias_manager.undefine_alias(aname)
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
@@ -273,7 +273,7 @@ def cd(self, parameter_s=''):
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 = {}
@@ -296,7 +296,7 @@ def cd(self, parameter_s=''):
ps = fallback
if ps is None:
- print "No matching entry in directory history"
+ print("No matching entry in directory history")
return
else:
opts = {}
@@ -320,7 +320,7 @@ def cd(self, parameter_s=''):
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:
@@ -336,7 +336,7 @@ def cd(self, parameter_s=''):
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']
@@ -355,7 +355,7 @@ def cd(self, parameter_s=''):
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
@@ -388,7 +388,7 @@ def popd(self, parameter_s=''):
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=''):
@@ -543,7 +543,7 @@ def sc(self, parameter_s=''):
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:
@@ -655,9 +655,9 @@ def bookmark(self, parameter_s=''):
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")
@@ -689,7 +689,7 @@ def pycat(self, parameter_s=''):
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)))
@@ -714,11 +714,11 @@ def file(self, line, cell):
if os.path.exists(filename):
if args.amend:
- print "Amending to %s" % filename
+ print("Amending 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.amend else 'w'
with io.open(filename, mode, encoding='utf-8') as f:
View
12 IPython/core/magics/script.py
@@ -220,20 +220,20 @@ def shebang(self, line, cell):
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)
@@ -258,7 +258,7 @@ def _run_script(self, p, cell):
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."""
View
36 IPython/core/profileapp.py
@@ -126,7 +126,7 @@ def parse_command_line(self, argv=None):
self.profile = self.extra_args[0]
def start(self):
- print self.profile_dir.location
+ print(self.profile_dir.location)
class ProfileList(Application):
@@ -157,35 +157,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=<name>"
- print
+ print()
+ print("To use any of the above profiles, start IPython with:")
+ print(" ipython --profile=<name>")
+ print()
def start(self):
self.list_profile_dirs()
@@ -297,8 +297,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)
View
10 IPython/core/pylabtools.py
@@ -71,7 +71,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
@@ -353,17 +353,17 @@ def pylab_activate(user_ns, gui=None, import_all=True, shell=None, welcome_messa
shell.pylab_gui_select = gui
# Otherwise if they are different
elif gui != pylab_gui_select:
- print ('Warning: Cannot change to a different GUI toolkit: %s.'
- ' Using %s instead.' % (gui, pylab_gui_select))
+ print(('Warning: Cannot change to a different GUI toolkit: %s.'
+ ' Using %s instead.' % (gui, pylab_gui_select)))
gui, backend = find_gui_and_backend(pylab_gui_select)
activate_matplotlib(backend)
import_pylab(user_ns, import_all)
if shell is not None:
configure_inline_support(shell, backend, user_ns)
if welcome_message:
- print """
+ print("""
Welcome to pylab, a matplotlib-based Python environment [backend: %s].
-For more information, type 'help(pylab)'.""" % backend
+For more information, type 'help(pylab)'.""" % backend)
# flush stdout, just to be safe
sys.stdout.flush()
View
2  IPython/core/tests/refbug.py
@@ -44,4 +44,4 @@ def f():
def call_f():
for func in cache:
- print 'lowercased:',func().lower()
+ print('lowercased:',func().lower())
View
2  IPython/core/tests/test_debugger.py
@@ -36,7 +36,7 @@ def __init__(self, lines):
def readline(self):
line = next(self.lines)
- print line
+ print(line)
return line+'\n'
class PdbTestInput(object):
View
6 IPython/core/tests/test_inputsplitter.py
@@ -755,10 +755,10 @@ def test_syntax_multiline_cell(self):
# 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
View
24 IPython/core/ultratb.py
@@ -1021,7 +1021,7 @@ def __call__(self, etype=None, evalue=None, etb=None):
try:
self.debugger()
except KeyboardInterrupt:
- print "\nKeyboardInterrupt"
+ print("\nKeyboardInterrupt")
#----------------------------------------------------------------------------
class FormattedTB(VerboseTB, ListTB):
@@ -1152,7 +1152,7 @@ def __call__(self,etype=None,evalue=None,etb=None,
try:
self.debugger()
except KeyboardInterrupt:
- print "\nKeyboardInterrupt"
+ print("\nKeyboardInterrupt")
def structured_traceback(self, etype=None, value=None, tb=None,
tb_offset=None, context=5):
@@ -1211,27 +1211,27 @@ def eggs(f, g, z=globals()):
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('')
View
10 IPython/deathrow/Gnuplot2.py
@@ -125,7 +125,7 @@ def eps_fix_bbox(fname):
# note: ps2ps and eps2eps do NOT work, ONLY ps2eps works correctly. The
# others make output with bitmapped fonts, which looks horrible.
- print 'Fixing eps file: <%s>' % fname
+ print('Fixing eps file: <%s>' % fname)
xsys('ps2eps -f -q -l %s' % fname)
if fname.endswith('.eps'):
os.rename(fname+'.eps',fname)
@@ -646,8 +646,8 @@ def hardcopy(self, filename=None,
time.sleep(0.05) # safety, very small delay
if os.path.isfile(filename):
if debug:
- print 'Hardcopy to file <%s> success at attempt #%s.' \
- % (filename,i+1)
+ print('Hardcopy to file <%s> success at attempt #%s.' \
+ % (filename,i+1))
break
time.sleep(delay)
# try again, issue all commands just in case
@@ -655,8 +655,8 @@ def hardcopy(self, filename=None,
self.set_string('output', filename)
self.refresh()
if not os.path.isfile(filename):
- print >> sys.stderr,'ERROR: Tried %s times and failed to '\
- 'create hardcopy file `%s`' % (maxtries,filename)
+ print('ERROR: Tried %s times and failed to '\
+ 'create hardcopy file `%s`' % (maxtries,filename), file=sys.stderr)
# reset the terminal to its `default' setting:
self('set terminal %s' % gp.GnuplotOpts.default_term)
View
2  IPython/deathrow/GnuplotInteractive.py
@@ -138,7 +138,7 @@ def magic_gp_set_default(self,parameter_s=''):
__IPYTHON__.gnuplot = GRun.gp
__IPYTHON__.gnuplot.shell_first_time = 1
- print """*** Type `gphelp` for help on the Gnuplot integration features."""
+ print("""*** Type `gphelp` for help on the Gnuplot integration features.""")
# Add the new magic functions to the class dict
from IPython.core.iplib import InteractiveShell
View
2  IPython/deathrow/GnuplotRuntime.py
@@ -82,7 +82,7 @@
gnu_out = getoutput('gnuplot '+ tmpname)
os.unlink(tmpname)
if gnu_out: # Gnuplot won't print anything if it has mouse support
- print "*** Your version of Gnuplot appears not to have mouse support."
+ print("*** Your version of Gnuplot appears not to have mouse support.")
gnuplot_mouse = 0
else:
gnuplot_mouse = 1
View
2  IPython/deathrow/PhysicalQInput.py
@@ -81,4 +81,4 @@ def prefilter_PQ(self,line,continuation):
del InteractiveShell,prefilter_PQ
# Just a heads up at the console
-print '*** Simplified input for physical quantities enabled.'
+print('*** Simplified input for physical quantities enabled.')
View
2  IPython/deathrow/dtutils.py
@@ -93,7 +93,7 @@ def idoctest(ns=None,eraise=False):
except EOFError:
pass
except KeyboardInterrupt:
- print "KeyboardInterrupt - Discarding input."
+ print("KeyboardInterrupt - Discarding input.")
run_test = False
ip.reloadhist()
View
4 IPython/deathrow/gui/wx/ipshell_nonblocking.py
@@ -179,7 +179,7 @@ def init_ipython0(self, user_ns={}, user_global_ns=None,
#we disable cpaste magic... until we found a way to use it properly.
def bypass_magic(self, arg):
- print '%this magic is currently disabled.'
+ print('%this magic is currently disabled.')
ipython0.define_magic('cpaste', bypass_magic)
import __builtin__
@@ -513,6 +513,6 @@ def _shell(self, ip, cmd):
#we use print command because the shell command is called
#inside IPython instance and thus is redirected to thread cout
#"\x01\x1b[1;36m\x02" <-- add colour to the text...
- print "\x01\x1b[1;36m\x02"+result
+ print("\x01\x1b[1;36m\x02"+result)
stdout.close()
stdin.close()
View
4 IPython/deathrow/gui/wx/wxIPython.py
@@ -142,12 +142,12 @@ def optionLoad(self):
elif key in options_history_panel.keys():
options_history_panel[key]['value'] = value
else:
- print >>sys.__stdout__,"Warning: key ",key,"not found in widget options. Check Options.conf"
+ print("Warning: key ",key,"not found in widget options. Check Options.conf", file=sys.__stdout__)
self.ipython_panel.reloadOptions(options_ipython_panel)
self.history_panel.reloadOptions(options_history_panel)
except IOError:
- print >>sys.__stdout__,"Could not open Options.conf, defaulting to default values."
+ print("Could not open Options.conf, defaulting to default values.", file=sys.__stdout__)
def createMenu(self):
View
2  IPython/deathrow/ipipe.py
@@ -2041,7 +2041,7 @@ def display(self):
finally:
pager.close()
except Exception as exc:
- print "%s: %s" % (exc.__class__.__name__, str(exc))
+ print("%s: %s" % (exc.__class__.__name__, str(exc)))
class _RedirectIO(object):
View
8 IPython/deathrow/ipy_kitcfg.py
@@ -35,7 +35,7 @@ def kitroot():
def main():
if not kitroot():
- print "Can't configure ipykit, IPYKITROOT should be set."
+ print("Can't configure ipykit, IPYKITROOT should be set.")
return
os.environ["PATH"] = os.environ["PATH"] + ";" + kitroot() + "\\bin;"
@@ -46,7 +46,7 @@ def main():
cmds = ip.db.get('syscmdlist', [])
#print cmds
if 'sc1' in cmds:
- print "Default editor: Sc1"
+ print("Default editor: Sc1")
import ipy_editors
ipy_editors.scite('sc1')
@@ -61,7 +61,7 @@ def main():
def ipython_firstrun(ip):
- print "First run of ipykit - configuring"
+ print("First run of ipykit - configuring")
ip.define_alias('py',selflaunch)
ip.define_alias('d','dir /w /og /on')
@@ -70,7 +70,7 @@ def ipython_firstrun(ip):
bins = kitroot() +'/bin'
- print greeting
+ print(greeting)
def init_ipython(ipy):
global ip
View
2  IPython/deathrow/ipy_profile_numpy.py
@@ -19,6 +19,6 @@ def main():
ip.ex("from numpy import *")
except ImportError:
- print "Unable to start NumPy profile, is numpy installed?"
+ print("Unable to start NumPy profile, is numpy installed?")
main()
View
2  IPython/deathrow/ipy_profile_scipy.py
@@ -24,6 +24,6 @@ def main():
ip.ex("from scipy import *")
except ImportError:
- print "Unable to start scipy profile, are numpy and scipy installed?"
+ print("Unable to start scipy profile, are numpy and scipy installed?")
main()
View
4 IPython/deathrow/ipy_profile_sh.py
@@ -88,11 +88,11 @@ def main():
syscmds = db.get("syscmdlist",[] )
if not syscmds:
- print textwrap.dedent("""
+ print(textwrap.dedent("""
System command list not initialized, probably the first run...
running %rehashx to refresh the command list. Run %rehashx
again to refresh command list (after installing new software etc.)
- """)
+ """))
ip.magic('rehashx')
syscmds = db.get("syscmdlist")
View
24 IPython/deathrow/ipy_profile_zope.py
@@ -50,8 +50,8 @@ def __init__(self):
if configfile is None:
raise RuntimeError( "CONFIG_FILE env not set" )
- print "CONFIG_FILE=", configfile
- print "INSTANCE_HOME=", self.instancehome
+ print("CONFIG_FILE=", configfile)
+ print("INSTANCE_HOME=", self.instancehome)
self.configfile = configfile
@@ -74,9 +74,9 @@ def __init__(self):
try:
self._make_permissive()
- print "Permissive security installed"
+ print("Permissive security installed")
except:
- print "Permissive security NOT installed"
+ print("Permissive security NOT installed")
self._pwd = self.portal or self.app
@@ -92,7 +92,7 @@ def __init__(self):
sm = getSiteManager()
if sm is gsm:
- print "ERROR SETTING SITE!"
+ print("ERROR SETTING SITE!")
except:
pass
@@ -150,7 +150,7 @@ def su(self, username):
# TODO Make it easy to change back to permissive security.
user = self.portal.acl_users.getUser(username)
if not user:
- print "Can't find %s in %s" % (username, self.portal.acl_users)
+ print("Can't find %s in %s" % (username, self.portal.acl_users))
return
from AccessControl import ZopeSecurityPolicy
@@ -162,7 +162,7 @@ def su(self, username):
self.oldpolicy = setSecurityPolicy(_policy)
wrapped_user = user.__of__(self.portal.acl_users)
newSecurityManager(None, user)
- print 'User changed.'
+ print('User changed.')
return getSecurityManager().getUser()
def getCatalogInfo(self, obj=None, catalog='portal_catalog', query=None, sort_on='created', sort_order='reverse' ):
@@ -170,7 +170,7 @@ def getCatalogInfo(self, obj=None, catalog='portal_catalog', query=None, sort_on
default query on that object, or pass an explicit query.
"""
if obj and query:
- print "Ignoring %s, using query." % obj
+ print("Ignoring %s, using query." % obj)
catalog = self.portal.get(catalog)
if not catalog:
@@ -260,7 +260,7 @@ def cd( self, path ):
if x is None:
raise KeyError( "Can't cd to %s" % path )
- print "%s -> %s" % ( self.pwd().getId(), x.getId() )
+ print("%s -> %s" % ( self.pwd().getId(), x.getId() ))
self._pwd = x
def ls( self, x=None ):
@@ -291,7 +291,7 @@ def main():
SOFTWARE_HOME = os.environ.get( "SOFTWARE_HOME" )
sys.path.append( SOFTWARE_HOME )
- print "SOFTWARE_HOME=%s\n" % SOFTWARE_HOME
+ print("SOFTWARE_HOME=%s\n" % SOFTWARE_HOME)
zope_debug = ZopeDebug()
@@ -303,7 +303,7 @@ def main():
# I like my banner minimal.
o.banner = "ZOPE Py %s IPy %s\n" % (sys.version.split('\n')[0],release.version)
- print textwrap.dedent("""\
+ print(textwrap.dedent("""\
ZOPE mode iPython shell.
Bound names:
@@ -313,7 +313,7 @@ def main():
Uses the $SOFTWARE_HOME and $CONFIG_FILE environment
variables.
- """ % ( ",".join([ x for x in dir(zope_debug.utils) if not x.startswith("_") ] ) ) )
+ """ % ( ",".join([ x for x in dir(zope_debug.utils) if not x.startswith("_") ] ) ) ))
sys.stdin = sys_oldstdin
View
2  IPython/deathrow/ipy_traits_completer.py
@@ -216,4 +216,4 @@ class Bunch(object): pass
# time...
ta = ip.complete('t.edi')
assert ta == ['t.edit_traits', 't.editable_traits']
- print 'Tests OK'
+ print('Tests OK')
View
10 IPython/deathrow/numeric_formats.py
@@ -15,9 +15,9 @@ def num_display(self,arg):
return
# Otherwise, we do work.
format = __IPYTHON__.runtime_rc.numarray_print_format
- print 'NumPy array, format:',format
+ print('NumPy array, format:',format)
# Here is where all the printing logic needs to be implemented
- print arg # nothing yet :)
+ print(arg) # nothing yet :)
def magic_format(self,parameter_s=''):
@@ -30,10 +30,10 @@ def magic_format(self,parameter_s=''):
if parameter_s in valid_formats:
self.runtime_rc.numarray_print_format = parameter_s
- print 'Numeric output format is now:',parameter_s
+ print('Numeric output format is now:',parameter_s)
else:
- print 'Invalid format:',parameter_s
- print 'Valid formats:',valid_formats
+ print('Invalid format:',parameter_s)
+ print('Valid formats:',valid_formats)
# setup default format
__IPYTHON__.runtime_rc.numarray_print_format = 'long'
View
4 IPython/deathrow/oldfrontend/cocoa/cocoa_frontend.py
@@ -293,7 +293,7 @@ def _store_engine_namespace_values(self, values, keys=[]):
def update_cell_prompt(self, result, blockID=None):
- print self.blockRanges
+ print(self.blockRanges)
if(isinstance(result, Failure)):
prompt = self.input_prompt()
@@ -325,7 +325,7 @@ def render_result(self, result):
def render_error(self, failure):
- print failure
+ print(failure)
blockID = failure.blockID
inputRange = self.blockRanges[blockID].inputRange
self.insert_text('\n' +
View
10 IPython/deathrow/oldfrontend/linefrontendbase.py
@@ -177,7 +177,7 @@ def write(self, string, refresh=True):
event loop, to choose whether the write should trigget an UI
refresh, and thus be syncrhonous, or not.
"""
- print >>sys.__stderr__, string
+ print(string, file=sys.__stderr__)
def execute(self, python_string, raw_string=None):
@@ -231,7 +231,7 @@ def complete_current_input(self):
""" Do code completion on current line.
"""
if self.debug:
- print >>sys.__stdout__, "complete_current_input",
+ print("complete_current_input", end=' ', file=sys.__stdout__)
line = self.input_buffer
new_line, completions = self.complete(line)
if len(completions)>1:
@@ -239,9 +239,9 @@ def complete_current_input(self):
elif not line == new_line:
self.input_buffer = new_line
if self.debug:
- print >>sys.__stdout__, 'line', line
- print >>sys.__stdout__, 'new_line', new_line
- print >>sys.__stdout__, completions
+ print('line', line, file=sys.__stdout__)
+ print('new_line', new_line, file=sys.__stdout__)
+ print(completions, file=sys.__stdout__)
def get_line_width(self):
View
2  IPython/deathrow/oldfrontend/prefilterfrontend.py
@@ -138,7 +138,7 @@ def show_traceback(self):
def execute(self, python_string, raw_string=None):
if self.debug:
- print 'Executing Python code:', repr(python_string)
+ print('Executing Python code:', repr(python_string))
self.capture_output()
LineFrontEndBase.execute(self, python_string,
raw_string=raw_string)
View
12 IPython/deathrow/oldfrontend/wx/wx_frontend.py
@@ -191,7 +191,7 @@ def do_calltip(self):
""" Analyse current and displays useful calltip for it.
"""
if self.debug:
- print >>sys.__stdout__, "do_calltip"
+ print("do_calltip", file=sys.__stdout__)
separators = re.compile('[\s\{\}\[\]\(\)\= ,:]')
symbol = self.input_buffer
symbol_string = separators.split(symbol)[-1]
@@ -221,7 +221,7 @@ def _popup_completion(self, create=False):
true, open the menu.
"""
if self.debug:
- print >>sys.__stdout__, "_popup_completion"
+ print("_popup_completion", file=sys.__stdout__)
line = self.input_buffer
if (self.AutoCompActive() and line and not line[-1] == '.') \
or create==True:
@@ -230,7 +230,7 @@ def _popup_completion(self, create=False):
offset = len(self._get_completion_text(line))
self.pop_completion(completions, offset=offset)
if self.debug:
- print >>sys.__stdout__, completions
+ print(completions, file=sys.__stdout__)
def buffered_write(self, text):
@@ -394,12 +394,12 @@ def _on_key_down(self, event, skip=True):
# Capture Control-C
if self._input_state == 'subprocess':
if self.debug:
- print >>sys.__stderr__, 'Killing running process'
+ print('Killing running process', file=sys.__stderr__)
if hasattr(self._running_process, 'process'):
self._running_process.process.kill()
elif self._input_state == 'buffering':
if self.debug:
- print >>sys.__stderr__, 'Raising KeyboardInterrupt'
+ print('Raising KeyboardInterrupt', file=sys.__stderr__)
raise KeyboardInterrupt
# XXX: We need to make really sure we
# get back to a prompt.
@@ -523,7 +523,7 @@ def _on_enter(self):
current_line_num = self.LineFromPosition(self.GetCurrentPos())
new_line_pos = (last_line_num - current_line_num)
if self.debug:
- print >>sys.__stdout__, repr(self.input_buffer)
+ print(repr(self.input_buffer), file=sys.__stdout__)
self.write('\n', refresh=False)
# Under windows scintilla seems to be doing funny
# stuff to the line returns here, but the getter for
View
40 IPython/deathrow/outputtrap.py
@@ -207,45 +207,45 @@ def _test_all():
def _test_():
name = ''
- print '#'*50+'\nRunning test for ' + name
+ print('#'*50+'\nRunning test for ' + name)
# ...
- print 'Finished test for '+ name +'\n'+'#'*50
+ print('Finished test for '+ name +'\n'+'#'*50)
def _test_OutputTrap():
trap = OutputTrap(name = 'Test Trap', sum_sep = '.'*50+'\n',
out_head = 'SOut. ', err_head = 'SErr. ')
name = 'OutputTrap class'
- print '#'*50+'\nRunning test for ' + name
- print 'Trapping out'
+ print('#'*50+'\nRunning test for ' + name)
+ print('Trapping out')
trap.trap_out()
- print >>sys.stdout, '>>stdout. stdout is trapped.'
- print >>sys.stderr, '>>stderr. stdout is trapped.'
+ print('>>stdout. stdout is trapped.', file=sys.stdout)
+ print('>>stderr. stdout is trapped.', file=sys.stderr)
trap.release_out()
- print trap.summary_out()
+ print(trap.summary_out())
- print 'Trapping err'
+ print('Trapping err')
trap.trap_err()
- print >>sys.stdout, '>>stdout. stderr is trapped.'
- print >>sys.stderr, '>>stderr. stderr is trapped.'
+ print('>>stdout. stderr is trapped.', file=sys.stdout)
+ print('>>stderr. stderr is trapped.', file=sys.stderr)
trap.release_err()
- print trap.summary_err()
+ print(trap.summary_err())
- print 'Trapping all (no flushing)'
+ print('Trapping all (no flushing)')
trap.trap_all()
- print >>sys.stdout, '>>stdout. stdout/err is trapped.'
- print >>sys.stderr, '>>stderr. stdout/err is trapped.'
+ print('>>stdout. stdout/err is trapped.', file=sys.stdout)
+ print('>>stderr. stdout/err is trapped.', file=sys.stderr)
trap.release_all()
- print trap.summary_all()
+ print(trap.summary_all())
- print 'Trapping all (flushing first)'
+ print('Trapping all (flushing first)')
trap.flush()
trap.trap_all()
- print >>sys.stdout, '>>stdout. stdout/err is trapped.'
- print >>sys.stderr, '>>stderr. stdout/err is trapped.'
+ print('>>stdout. stdout/err is trapped.', file=sys.stdout)
+ print('>>stderr. stdout/err is trapped.', file=sys.stderr)
trap.release_all()
- print trap.summary_all()
- print 'Finished test for '+ name +'\n'+'#'*50
+ print(trap.summary_all())
+ print('Finished test for '+ name +'\n'+'#'*50)
# call the actual tests here:
_test_OutputTrap()
View
8 IPython/deathrow/tests/test_prefilter.py
@@ -431,10 +431,10 @@ def __call__(self):
# ============
num_f = len(failures)
if verbose:
- print
-print "%s tests run, %s failure%s" % (num_tests,
+ print()
+print("%s tests run, %s failure%s" % (num_tests,
num_f,
- num_f != 1 and "s" or "")
+ num_f != 1 and "s" or ""))
for f in failures:
- print f
+ print(f)
View
16 IPython/deathrow/twshell.py
@@ -130,8 +130,8 @@ def runsource(self, source, filename="<input>", symbol="single"):
received_ev.wait(5)
if not received_ev.isSet():
# the mainloop is dead, start executing code directly
- print "Warning: Timeout for mainloop thread exceeded"
- print "switching to nonthreaded mode (until mainloop wakes up again)"
+ print("Warning: Timeout for mainloop thread exceeded")
+ print("switching to nonthreaded mode (until mainloop wakes up again)")
self.worker_ident = None
else:
completed_ev.wait()
@@ -148,11 +148,11 @@ def runcode(self):
self.worker_ident = thread.get_ident()
if self._kill:
- print >>Term.cout, 'Closing threads...',
+ print('Closing threads...', end=' ', file=Term.cout)
Term.cout.flush()
for tokill in self.on_kill:
tokill()
- print >>Term.cout, 'Done.'
+ print('Done.', file=Term.cout)
# allow kill() to return
self._kill.set()
return True
@@ -189,7 +189,7 @@ def runcode(self):
shellglobals.CODE_RUN = True
InteractiveShell.runcode(self,code_to_run)
except KeyboardInterrupt:
- print "Keyboard interrupted in mainloop"
+ print("Keyboard interrupted in mainloop")
while not self.code_queue.empty():
code = self.code_queue.get_nowait()
break
@@ -251,14 +251,14 @@ def run(self):
def mainloop(self):
def mainLoopThreadDeath(r):
- print "mainLoopThreadDeath: ", str(r)
+ print("mainLoopThreadDeath: ", str(r))
def spawnMainloopThread():
d=threads.deferToThread(self.run)
d.addBoth(mainLoopThreadDeath)
reactor.callWhenRunning(spawnMainloopThread)
self.IP.reactor_started = True
self.reactor.run()
- print "mainloop ending...."
+ print("mainloop ending....")
exists = True
@@ -283,5 +283,5 @@ def spawnMainloopThread():
shell.mainloop()
# You must exit IPython to terminate your program.
- print 'Goodbye!'
+ print('Goodbye!')
View
20 IPython/extensions/storemagic.py
@@ -52,8 +52,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
@@ -147,13 +147,13 @@ def store(self, parameter_s=''):
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, '<unavailable>'))[:50])
+ print(fmt % (justkey, repr(get(var, '<unavailable>'))[:50]))
# default action - store the variable
else:
@@ -165,8 +165,8 @@ def store(self, parameter_s=''):
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):
@@ -192,23 +192,23 @@ def store(self, parameter_s=''):
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:
raise UsageError("Unknown variable '%s'" % args[0])
else:
if isinstance(inspect.getmodule(obj), FakeModule):
- 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__))
class StoreMagic(Plugin):
View
4 IPython/external/decorator/_decorator.py
@@ -162,8 +162,8 @@ def make(self, src_templ, evaldict=None, addsource=False, **attrs):
# print >> sys.stderr, 'Compiling %s' % src
exec code in evaldict
except:
- print >> sys.stderr, 'Error in generated code:'
- print >> sys.stderr, src