##// END OF EJS Templates
Convert print statements to print function calls...
Thomas Kluyver -
r13348:e6afea51
parent child
Show More
@@ -7,6 +7,7 Authors:
7 * Brian Granger
7 * Brian Granger
8 * Min RK
8 * Min RK
9 """
9 """
10 from __future__ import print_function
10
11
11 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2011 The IPython Development Team
13 # Copyright (C) 2008-2011 The IPython Development Team
@@ -286,7 +287,7 class Application(SingletonConfigurable):
286 help[0] = help[0].replace('--%s='%alias, '-%s '%alias)
287 help[0] = help[0].replace('--%s='%alias, '-%s '%alias)
287 lines.extend(help)
288 lines.extend(help)
288 # lines.append('')
289 # lines.append('')
289 print os.linesep.join(lines)
290 print(os.linesep.join(lines))
290
291
291 def print_flag_help(self):
292 def print_flag_help(self):
292 """Print the flag part of the help."""
293 """Print the flag part of the help."""
@@ -299,7 +300,7 class Application(SingletonConfigurable):
299 lines.append(prefix+m)
300 lines.append(prefix+m)
300 lines.append(indent(dedent(help.strip())))
301 lines.append(indent(dedent(help.strip())))
301 # lines.append('')
302 # lines.append('')
302 print os.linesep.join(lines)
303 print(os.linesep.join(lines))
303
304
304 def print_options(self):
305 def print_options(self):
305 if not self.flags and not self.aliases:
306 if not self.flags and not self.aliases:
@@ -310,10 +311,10 class Application(SingletonConfigurable):
310 for p in wrap_paragraphs(self.option_description):
311 for p in wrap_paragraphs(self.option_description):
311 lines.append(p)
312 lines.append(p)
312 lines.append('')
313 lines.append('')
313 print os.linesep.join(lines)
314 print(os.linesep.join(lines))
314 self.print_flag_help()
315 self.print_flag_help()
315 self.print_alias_help()
316 self.print_alias_help()
316 print
317 print()
317
318
318 def print_subcommands(self):
319 def print_subcommands(self):
319 """Print the subcommand part of the help."""
320 """Print the subcommand part of the help."""
@@ -331,7 +332,7 class Application(SingletonConfigurable):
331 if help:
332 if help:
332 lines.append(indent(dedent(help.strip())))
333 lines.append(indent(dedent(help.strip())))
333 lines.append('')
334 lines.append('')
334 print os.linesep.join(lines)
335 print(os.linesep.join(lines))
335
336
336 def print_help(self, classes=False):
337 def print_help(self, classes=False):
337 """Print the help for each Configurable class in self.classes.
338 """Print the help for each Configurable class in self.classes.
@@ -344,19 +345,19 class Application(SingletonConfigurable):
344
345
345 if classes:
346 if classes:
346 if self.classes:
347 if self.classes:
347 print "Class parameters"
348 print("Class parameters")
348 print "----------------"
349 print("----------------")
349 print
350 print()
350 for p in wrap_paragraphs(self.keyvalue_description):
351 for p in wrap_paragraphs(self.keyvalue_description):
351 print p
352 print(p)
352 print
353 print()
353
354
354 for cls in self.classes:
355 for cls in self.classes:
355 cls.class_print_help()
356 cls.class_print_help()
356 print
357 print()
357 else:
358 else:
358 print "To see all available configurables, use `--help-all`"
359 print("To see all available configurables, use `--help-all`")
359 print
360 print()
360
361
361 self.print_examples()
362 self.print_examples()
362
363
@@ -364,8 +365,8 class Application(SingletonConfigurable):
364 def print_description(self):
365 def print_description(self):
365 """Print the application description."""
366 """Print the application description."""
366 for p in wrap_paragraphs(self.description):
367 for p in wrap_paragraphs(self.description):
367 print p
368 print(p)
368 print
369 print()
369
370
370 def print_examples(self):
371 def print_examples(self):
371 """Print usage and examples.
372 """Print usage and examples.
@@ -374,15 +375,15 class Application(SingletonConfigurable):
374 and should contain examples of the application's usage.
375 and should contain examples of the application's usage.
375 """
376 """
376 if self.examples:
377 if self.examples:
377 print "Examples"
378 print("Examples")
378 print "--------"
379 print("--------")
379 print
380 print()
380 print indent(dedent(self.examples.strip()))
381 print(indent(dedent(self.examples.strip())))
381 print
382 print()
382
383
383 def print_version(self):
384 def print_version(self):
384 """Print the version string."""
385 """Print the version string."""
385 print self.version
386 print(self.version)
386
387
387 def update_config(self, config):
388 def update_config(self, config):
388 """Fire the traits events when the config is updated."""
389 """Fire the traits events when the config is updated."""
@@ -13,6 +13,7 Authors:
13 * Fernando Perez
13 * Fernando Perez
14 * Min RK
14 * Min RK
15 """
15 """
16 from __future__ import print_function
16
17
17 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
18 # Copyright (C) 2008-2011 The IPython Development Team
19 # Copyright (C) 2008-2011 The IPython Development Team
@@ -236,7 +237,7 class Configurable(HasTraits):
236 @classmethod
237 @classmethod
237 def class_print_help(cls, inst=None):
238 def class_print_help(cls, inst=None):
238 """Get the help string for a single trait and print it."""
239 """Get the help string for a single trait and print it."""
239 print cls.class_get_help(inst)
240 print(cls.class_get_help(inst))
240
241
241 @classmethod
242 @classmethod
242 def class_config_section(cls):
243 def class_config_section(cls):
@@ -1,5 +1,6
1 """Logger class for IPython's logging facilities.
1 """Logger class for IPython's logging facilities.
2 """
2 """
3 from __future__ import print_function
3
4
4 #*****************************************************************************
5 #*****************************************************************************
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
@@ -137,33 +138,33 class Logger(object):
137 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
138 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
138
139
139 if self.logfile is None:
140 if self.logfile is None:
140 print """
141 print("""
141 Logging hasn't been started yet (use logstart for that).
142 Logging hasn't been started yet (use logstart for that).
142
143
143 %logon/%logoff are for temporarily starting and stopping logging for a logfile
144 %logon/%logoff are for temporarily starting and stopping logging for a logfile
144 which already exists. But you must first start the logging process with
145 which already exists. But you must first start the logging process with
145 %logstart (optionally giving a logfile name)."""
146 %logstart (optionally giving a logfile name).""")
146
147
147 else:
148 else:
148 if self.log_active == val:
149 if self.log_active == val:
149 print 'Logging is already',label[val]
150 print('Logging is already',label[val])
150 else:
151 else:
151 print 'Switching logging',label[val]
152 print('Switching logging',label[val])
152 self.log_active = not self.log_active
153 self.log_active = not self.log_active
153 self.log_active_out = self.log_active
154 self.log_active_out = self.log_active
154
155
155 def logstate(self):
156 def logstate(self):
156 """Print a status message about the logger."""
157 """Print a status message about the logger."""
157 if self.logfile is None:
158 if self.logfile is None:
158 print 'Logging has not been activated.'
159 print('Logging has not been activated.')
159 else:
160 else:
160 state = self.log_active and 'active' or 'temporarily suspended'
161 state = self.log_active and 'active' or 'temporarily suspended'
161 print 'Filename :',self.logfname
162 print('Filename :',self.logfname)
162 print 'Mode :',self.logmode
163 print('Mode :',self.logmode)
163 print 'Output logging :',self.log_output
164 print('Output logging :',self.log_output)
164 print 'Raw input log :',self.log_raw_input
165 print('Raw input log :',self.log_raw_input)
165 print 'Timestamping :',self.timestamp
166 print('Timestamping :',self.timestamp)
166 print 'State :',state
167 print('State :',state)
167
168
168 def log(self, line_mod, line_ori):
169 def log(self, line_mod, line_ori):
169 """Write the sources to a log.
170 """Write the sources to a log.
@@ -213,7 +214,7 which already exists. But you must first start the logging process with
213 self.logfile.close()
214 self.logfile.close()
214 self.logfile = None
215 self.logfile = None
215 else:
216 else:
216 print "Logging hadn't been started."
217 print("Logging hadn't been started.")
217 self.log_active = False
218 self.log_active = False
218
219
219 # For backwards compatibility, in case anyone was using this.
220 # For backwards compatibility, in case anyone was using this.
@@ -1,6 +1,7
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4 from __future__ import print_function
4
5
5 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
@@ -544,8 +545,8 class Magics(Configurable):
544
545
545 def arg_err(self,func):
546 def arg_err(self,func):
546 """Print docstring if incorrect arguments were passed"""
547 """Print docstring if incorrect arguments were passed"""
547 print 'Error in arguments:'
548 print('Error in arguments:')
548 print oinspect.getdoc(func)
549 print(oinspect.getdoc(func))
549
550
550 def format_latex(self, strng):
551 def format_latex(self, strng):
551 """Format a string for latex inclusion."""
552 """Format a string for latex inclusion."""
@@ -1,5 +1,6
1 """Implementation of magic functions that control various automatic behaviors.
1 """Implementation of magic functions that control various automatic behaviors.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -57,7 +58,7 class AutoMagics(Magics):
57 else:
58 else:
58 val = not mman.auto_magic
59 val = not mman.auto_magic
59 mman.auto_magic = val
60 mman.auto_magic = val
60 print '\n' + self.shell.magics_manager.auto_status()
61 print('\n' + self.shell.magics_manager.auto_status())
61
62
62 @skip_doctest
63 @skip_doctest
63 @line_magic
64 @line_magic
@@ -125,4 +126,4 class AutoMagics(Magics):
125 except AttributeError:
126 except AttributeError:
126 self.shell.autocall = self._magic_state.autocall_save = 1
127 self.shell.autocall = self._magic_state.autocall_save = 1
127
128
128 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
129 print("Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall])
@@ -1,5 +1,6
1 """Implementation of code management magic functions.
1 """Implementation of code management magic functions.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -189,15 +190,15 class CodeMagics(Magics):
189 try:
190 try:
190 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
191 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
191 except StdinNotImplementedError:
192 except StdinNotImplementedError:
192 print "File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s)
193 print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
193 return
194 return
194 if not overwrite :
195 if not overwrite :
195 print 'Operation cancelled.'
196 print('Operation cancelled.')
196 return
197 return
197 try:
198 try:
198 cmds = self.shell.find_user_code(codefrom,raw)
199 cmds = self.shell.find_user_code(codefrom,raw)
199 except (TypeError, ValueError) as e:
200 except (TypeError, ValueError) as e:
200 print e.args[0]
201 print(e.args[0])
201 return
202 return
202 out = py3compat.cast_unicode(cmds)
203 out = py3compat.cast_unicode(cmds)
203 with io.open(fname, mode, encoding="utf-8") as f:
204 with io.open(fname, mode, encoding="utf-8") as f:
@@ -207,8 +208,8 class CodeMagics(Magics):
207 # make sure we end on a newline
208 # make sure we end on a newline
208 if not out.endswith(u'\n'):
209 if not out.endswith(u'\n'):
209 f.write(u'\n')
210 f.write(u'\n')
210 print 'The following commands were written to file `%s`:' % fname
211 print('The following commands were written to file `%s`:' % fname)
211 print cmds
212 print(cmds)
212
213
213 @line_magic
214 @line_magic
214 def pastebin(self, parameter_s=''):
215 def pastebin(self, parameter_s=''):
@@ -230,7 +231,7 class CodeMagics(Magics):
230 try:
231 try:
231 code = self.shell.find_user_code(args)
232 code = self.shell.find_user_code(args)
232 except (ValueError, TypeError) as e:
233 except (ValueError, TypeError) as e:
233 print e.args[0]
234 print(e.args[0])
234 return
235 return
235
236
236 from urllib2 import urlopen # Deferred import
237 from urllib2 import urlopen # Deferred import
@@ -337,7 +338,7 class CodeMagics(Magics):
337 ans = True
338 ans = True
338
339
339 if ans is False :
340 if ans is False :
340 print 'Operation cancelled.'
341 print('Operation cancelled.')
341 return
342 return
342
343
343 self.shell.set_next_input(contents)
344 self.shell.set_next_input(contents)
@@ -459,7 +460,7 class CodeMagics(Magics):
459
460
460 if use_temp:
461 if use_temp:
461 filename = shell.mktempfile(data)
462 filename = shell.mktempfile(data)
462 print 'IPython will make a temporary file named:',filename
463 print('IPython will make a temporary file named:',filename)
463
464
464 # use last_call to remember the state of the previous call, but don't
465 # use last_call to remember the state of the previous call, but don't
465 # let it be clobbered by successive '-p' calls.
466 # let it be clobbered by successive '-p' calls.
@@ -637,7 +638,7 class CodeMagics(Magics):
637 self._edit_macro(args, e.args[0])
638 self._edit_macro(args, e.args[0])
638 return
639 return
639 except InteractivelyDefined as e:
640 except InteractivelyDefined as e:
640 print "Editing In[%i]" % e.index
641 print("Editing In[%i]" % e.index)
641 args = str(e.index)
642 args = str(e.index)
642 filename, lineno, is_temp = self._find_edit_target(self.shell,
643 filename, lineno, is_temp = self._find_edit_target(self.shell,
643 args, opts, last_call)
644 args, opts, last_call)
@@ -647,7 +648,7 class CodeMagics(Magics):
647 return
648 return
648
649
649 # do actual editing here
650 # do actual editing here
650 print 'Editing...',
651 print('Editing...', end=' ')
651 sys.stdout.flush()
652 sys.stdout.flush()
652 try:
653 try:
653 # Quote filenames that may have spaces in them
654 # Quote filenames that may have spaces in them
@@ -665,9 +666,9 class CodeMagics(Magics):
665 self.shell.user_ns['pasted_block'] = f.read()
666 self.shell.user_ns['pasted_block'] = f.read()
666
667
667 if 'x' in opts: # -x prevents actual execution
668 if 'x' in opts: # -x prevents actual execution
668 print
669 print()
669 else:
670 else:
670 print 'done. Executing edited code...'
671 print('done. Executing edited code...')
671 with preserve_keys(self.shell.user_ns, '__file__'):
672 with preserve_keys(self.shell.user_ns, '__file__'):
672 if not is_temp:
673 if not is_temp:
673 self.shell.user_ns['__file__'] = filename
674 self.shell.user_ns['__file__'] = filename
@@ -1,5 +1,6
1 """Implementation of configuration-related magic functions.
1 """Implementation of configuration-related magic functions.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -116,9 +117,9 class ConfigMagics(Magics):
116 line = s.strip()
117 line = s.strip()
117 if not line:
118 if not line:
118 # print available configurable names
119 # print available configurable names
119 print "Available objects for config:"
120 print("Available objects for config:")
120 for name in classnames:
121 for name in classnames:
121 print " ", name
122 print(" ", name)
122 return
123 return
123 elif line in classnames:
124 elif line in classnames:
124 # `%config TerminalInteractiveShell` will print trait info for
125 # `%config TerminalInteractiveShell` will print trait info for
@@ -128,7 +129,7 class ConfigMagics(Magics):
128 help = cls.class_get_help(c)
129 help = cls.class_get_help(c)
129 # strip leading '--' from cl-args:
130 # strip leading '--' from cl-args:
130 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
131 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
131 print help
132 print(help)
132 return
133 return
133 elif reg.match(line):
134 elif reg.match(line):
134 cls, attr = line.split('.')
135 cls, attr = line.split('.')
@@ -1,5 +1,6
1 """Deprecated Magic functions.
1 """Deprecated Magic functions.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -26,20 +27,20 class DeprecatedMagics(Magics):
26 @line_magic
27 @line_magic
27 def install_profiles(self, parameter_s=''):
28 def install_profiles(self, parameter_s=''):
28 """%install_profiles has been deprecated."""
29 """%install_profiles has been deprecated."""
29 print '\n'.join([
30 print('\n'.join([
30 "%install_profiles has been deprecated.",
31 "%install_profiles has been deprecated.",
31 "Use `ipython profile list` to view available profiles.",
32 "Use `ipython profile list` to view available profiles.",
32 "Requesting a profile with `ipython profile create <name>`",
33 "Requesting a profile with `ipython profile create <name>`",
33 "or `ipython --profile=<name>` will start with the bundled",
34 "or `ipython --profile=<name>` will start with the bundled",
34 "profile of that name if it exists."
35 "profile of that name if it exists."
35 ])
36 ]))
36
37
37 @line_magic
38 @line_magic
38 def install_default_config(self, parameter_s=''):
39 def install_default_config(self, parameter_s=''):
39 """%install_default_config has been deprecated."""
40 """%install_default_config has been deprecated."""
40 print '\n'.join([
41 print('\n'.join([
41 "%install_default_config has been deprecated.",
42 "%install_default_config has been deprecated.",
42 "Use `ipython profile create <name>` to initialize a profile",
43 "Use `ipython profile create <name>` to initialize a profile",
43 "with the default config files.",
44 "with the default config files.",
44 "Add `--reset` to overwrite already existing config files with defaults."
45 "Add `--reset` to overwrite already existing config files with defaults."
45 ])
46 ]))
@@ -1,6 +1,7
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Implementation of execution-related magic functions.
2 """Implementation of execution-related magic functions.
3 """
3 """
4 from __future__ import print_function
4 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
5 # Copyright (c) 2012 The IPython Development Team.
6 # Copyright (c) 2012 The IPython Development Team.
6 #
7 #
@@ -277,22 +278,22 python-profiler package from non-free.""")
277
278
278 if 'q' not in opts:
279 if 'q' not in opts:
279 page.page(output)
280 page.page(output)
280 print sys_exit,
281 print(sys_exit, end=' ')
281
282
282 dump_file = opts.D[0]
283 dump_file = opts.D[0]
283 text_file = opts.T[0]
284 text_file = opts.T[0]
284 if dump_file:
285 if dump_file:
285 dump_file = unquote_filename(dump_file)
286 dump_file = unquote_filename(dump_file)
286 prof.dump_stats(dump_file)
287 prof.dump_stats(dump_file)
287 print '\n*** Profile stats marshalled to file',\
288 print('\n*** Profile stats marshalled to file',\
288 repr(dump_file)+'.',sys_exit
289 repr(dump_file)+'.',sys_exit)
289 if text_file:
290 if text_file:
290 text_file = unquote_filename(text_file)
291 text_file = unquote_filename(text_file)
291 pfile = open(text_file,'w')
292 pfile = open(text_file,'w')
292 pfile.write(output)
293 pfile.write(output)
293 pfile.close()
294 pfile.close()
294 print '\n*** Profile printout saved to text file',\
295 print('\n*** Profile printout saved to text file',\
295 repr(text_file)+'.',sys_exit
296 repr(text_file)+'.',sys_exit)
296
297
297 if 'r' in opts:
298 if 'r' in opts:
298 return stats
299 return stats
@@ -332,7 +333,7 python-profiler package from non-free.""")
332
333
333 # set on the shell
334 # set on the shell
334 self.shell.call_pdb = new_pdb
335 self.shell.call_pdb = new_pdb
335 print 'Automatic pdb calling has been turned',on_off(new_pdb)
336 print('Automatic pdb calling has been turned',on_off(new_pdb))
336
337
337 @skip_doctest
338 @skip_doctest
338 @magic_arguments.magic_arguments()
339 @magic_arguments.magic_arguments()
@@ -558,7 +559,7 python-profiler package from non-free.""")
558 filename = file_finder(arg_lst[0])
559 filename = file_finder(arg_lst[0])
559 except IndexError:
560 except IndexError:
560 warn('you must provide at least a filename.')
561 warn('you must provide at least a filename.')
561 print '\n%run:\n', oinspect.getdoc(self.run)
562 print('\n%run:\n', oinspect.getdoc(self.run))
562 return
563 return
563 except IOError as e:
564 except IOError as e:
564 try:
565 try:
@@ -775,7 +776,7 python-profiler package from non-free.""")
775 deb.mainpyfile = deb.canonic(filename)
776 deb.mainpyfile = deb.canonic(filename)
776
777
777 # Start file run
778 # Start file run
778 print "NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt
779 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
779 try:
780 try:
780 if filename:
781 if filename:
781 # save filename so it can be used by methods on the deb object
782 # save filename so it can be used by methods on the deb object
@@ -809,9 +810,9 python-profiler package from non-free.""")
809 t1 = clock2()
810 t1 = clock2()
810 t_usr = t1[0] - t0[0]
811 t_usr = t1[0] - t0[0]
811 t_sys = t1[1] - t0[1]
812 t_sys = t1[1] - t0[1]
812 print "\nIPython CPU timings (estimated):"
813 print("\nIPython CPU timings (estimated):")
813 print " User : %10.2f s." % t_usr
814 print(" User : %10.2f s." % t_usr)
814 print " System : %10.2f s." % t_sys
815 print(" System : %10.2f s." % t_sys)
815 else:
816 else:
816 runs = range(nruns)
817 runs = range(nruns)
817 t0 = clock2()
818 t0 = clock2()
@@ -820,13 +821,13 python-profiler package from non-free.""")
820 t1 = clock2()
821 t1 = clock2()
821 t_usr = t1[0] - t0[0]
822 t_usr = t1[0] - t0[0]
822 t_sys = t1[1] - t0[1]
823 t_sys = t1[1] - t0[1]
823 print "\nIPython CPU timings (estimated):"
824 print("\nIPython CPU timings (estimated):")
824 print "Total runs performed:", nruns
825 print("Total runs performed:", nruns)
825 print " Times : %10s %10s" % ('Total', 'Per run')
826 print(" Times : %10s %10s" % ('Total', 'Per run'))
826 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
827 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
827 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
828 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
828 twall1 = time.time()
829 twall1 = time.time()
829 print "Wall time: %10.2f s." % (twall1 - twall0)
830 print("Wall time: %10.2f s." % (twall1 - twall0))
830
831
831 @skip_doctest
832 @skip_doctest
832 @line_cell_magic
833 @line_cell_magic
@@ -989,10 +990,10 python-profiler package from non-free.""")
989 all_runs = timer.repeat(repeat, number)
990 all_runs = timer.repeat(repeat, number)
990 best = min(all_runs) / number
991 best = min(all_runs) / number
991 if not quiet :
992 if not quiet :
992 print u"%d loops, best of %d: %s per loop" % (number, repeat,
993 print(u"%d loops, best of %d: %s per loop" % (number, repeat,
993 _format_time(best, precision))
994 _format_time(best, precision)))
994 if tc > tc_min:
995 if tc > tc_min:
995 print "Compiler time: %.2f s" % tc
996 print("Compiler time: %.2f s" % tc)
996 if return_result:
997 if return_result:
997 return TimeitResult(number, repeat, best, all_runs, tc, precision)
998 return TimeitResult(number, repeat, best, all_runs, tc, precision)
998
999
@@ -1110,13 +1111,13 python-profiler package from non-free.""")
1110 cpu_tot = cpu_user+cpu_sys
1111 cpu_tot = cpu_user+cpu_sys
1111 # On windows cpu_sys is always zero, so no new information to the next print
1112 # On windows cpu_sys is always zero, so no new information to the next print
1112 if sys.platform != 'win32':
1113 if sys.platform != 'win32':
1113 print "CPU times: user %s, sys: %s, total: %s" % \
1114 print("CPU times: user %s, sys: %s, total: %s" % \
1114 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))
1115 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1115 print "Wall time: %s" % _format_time(wall_time)
1116 print("Wall time: %s" % _format_time(wall_time))
1116 if tc > tc_min:
1117 if tc > tc_min:
1117 print "Compiler : %s" % _format_time(tc)
1118 print("Compiler : %s" % _format_time(tc))
1118 if tp > tp_min:
1119 if tp > tp_min:
1119 print "Parser : %s" % _format_time(tp)
1120 print("Parser : %s" % _format_time(tp))
1120 return out
1121 return out
1121
1122
1122 @skip_doctest
1123 @skip_doctest
@@ -1195,14 +1196,14 python-profiler package from non-free.""")
1195 try:
1196 try:
1196 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1197 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1197 except (ValueError, TypeError) as e:
1198 except (ValueError, TypeError) as e:
1198 print e.args[0]
1199 print(e.args[0])
1199 return
1200 return
1200 macro = Macro(lines)
1201 macro = Macro(lines)
1201 self.shell.define_macro(name, macro)
1202 self.shell.define_macro(name, macro)
1202 if not ( 'q' in opts) :
1203 if not ( 'q' in opts) :
1203 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1204 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1204 print '=== Macro contents: ==='
1205 print('=== Macro contents: ===')
1205 print macro,
1206 print(macro, end=' ')
1206
1207
1207 @magic_arguments.magic_arguments()
1208 @magic_arguments.magic_arguments()
1208 @magic_arguments.argument('output', type=str, default='', nargs='?',
1209 @magic_arguments.argument('output', type=str, default='', nargs='?',
@@ -1,5 +1,6
1 """Implementation of magic functions for the extension machinery.
1 """Implementation of magic functions for the extension machinery.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -46,12 +47,12 class ExtensionMagics(Magics):
46 filename = self.shell.extension_manager.install_extension(args,
47 filename = self.shell.extension_manager.install_extension(args,
47 opts.get('n'))
48 opts.get('n'))
48 except ValueError as e:
49 except ValueError as e:
49 print e
50 print(e)
50 return
51 return
51
52
52 filename = os.path.basename(filename)
53 filename = os.path.basename(filename)
53 print "Installed %s. To use it, type:" % filename
54 print("Installed %s. To use it, type:" % filename)
54 print " %%load_ext %s" % os.path.splitext(filename)[0]
55 print(" %%load_ext %s" % os.path.splitext(filename)[0])
55
56
56
57
57 @line_magic
58 @line_magic
@@ -62,10 +63,10 class ExtensionMagics(Magics):
62 res = self.shell.extension_manager.load_extension(module_str)
63 res = self.shell.extension_manager.load_extension(module_str)
63
64
64 if res == 'already loaded':
65 if res == 'already loaded':
65 print "The %s extension is already loaded. To reload it, use:" % module_str
66 print("The %s extension is already loaded. To reload it, use:" % module_str)
66 print " %reload_ext", module_str
67 print(" %reload_ext", module_str)
67 elif res == 'no load function':
68 elif res == 'no load function':
68 print "The %s module is not an IPython extension." % module_str
69 print("The %s module is not an IPython extension." % module_str)
69
70
70 @line_magic
71 @line_magic
71 def unload_ext(self, module_str):
72 def unload_ext(self, module_str):
@@ -80,9 +81,9 class ExtensionMagics(Magics):
80 res = self.shell.extension_manager.unload_extension(module_str)
81 res = self.shell.extension_manager.unload_extension(module_str)
81
82
82 if res == 'no unload function':
83 if res == 'no unload function':
83 print "The %s extension doesn't define how to unload it." % module_str
84 print("The %s extension doesn't define how to unload it." % module_str)
84 elif res == "not loaded":
85 elif res == "not loaded":
85 print "The %s extension is not loaded." % module_str
86 print("The %s extension is not loaded." % module_str)
86
87
87 @line_magic
88 @line_magic
88 def reload_ext(self, module_str):
89 def reload_ext(self, module_str):
@@ -1,5 +1,6
1 """Implementation of namespace-related magic functions.
1 """Implementation of namespace-related magic functions.
2 """
2 """
3 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
5 #
6 #
@@ -117,7 +118,7 class NamespaceMagics(Magics):
117 try:
118 try:
118 filename = get_py_filename(parameter_s)
119 filename = get_py_filename(parameter_s)
119 except IOError as msg:
120 except IOError as msg:
120 print msg
121 print(msg)
121 return
122 return
122 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
123 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
123
124
@@ -204,7 +205,7 class NamespaceMagics(Magics):
204 try:
205 try:
205 parameter_s.encode('ascii')
206 parameter_s.encode('ascii')
206 except UnicodeEncodeError:
207 except UnicodeEncodeError:
207 print 'Python identifiers can only contain ascii characters.'
208 print('Python identifiers can only contain ascii characters.')
208 return
209 return
209
210
210 # default namespaces to be searched
211 # default namespaces to be searched
@@ -327,20 +328,20 class NamespaceMagics(Magics):
327 varlist = self.who_ls(parameter_s)
328 varlist = self.who_ls(parameter_s)
328 if not varlist:
329 if not varlist:
329 if parameter_s:
330 if parameter_s:
330 print 'No variables match your requested type.'
331 print('No variables match your requested type.')
331 else:
332 else:
332 print 'Interactive namespace is empty.'
333 print('Interactive namespace is empty.')
333 return
334 return
334
335
335 # if we have variables, move on...
336 # if we have variables, move on...
336 count = 0
337 count = 0
337 for i in varlist:
338 for i in varlist:
338 print i+'\t',
339 print(i+'\t', end=' ')
339 count += 1
340 count += 1
340 if count > 8:
341 if count > 8:
341 count = 0
342 count = 0
342 print
343 print()
343 print
344 print()
344
345
345 @skip_doctest
346 @skip_doctest
346 @line_magic
347 @line_magic
@@ -378,9 +379,9 class NamespaceMagics(Magics):
378 varnames = self.who_ls(parameter_s)
379 varnames = self.who_ls(parameter_s)
379 if not varnames:
380 if not varnames:
380 if parameter_s:
381 if parameter_s:
381 print 'No variables match your requested type.'
382 print('No variables match your requested type.')
382 else:
383 else:
383 print 'Interactive namespace is empty.'
384 print('Interactive namespace is empty.')
384 return
385 return
385
386
386 # if we have variables, move on...
387 # if we have variables, move on...
@@ -432,15 +433,15 class NamespaceMagics(Magics):
432 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
433 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
433 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
434 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
434 # table header
435 # table header
435 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
436 print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
436 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
437 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
437 # and the table itself
438 # and the table itself
438 kb = 1024
439 kb = 1024
439 Mb = 1048576 # kb**2
440 Mb = 1048576 # kb**2
440 for vname,var,vtype in zip(varnames,varlist,typelist):
441 for vname,var,vtype in zip(varnames,varlist,typelist):
441 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
442 print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
442 if vtype in seq_types:
443 if vtype in seq_types:
443 print "n="+str(len(var))
444 print("n="+str(len(var)))
444 elif vtype == ndarray_type:
445 elif vtype == ndarray_type:
445 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
446 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
446 if vtype==ndarray_type:
447 if vtype==ndarray_type:
@@ -450,13 +451,13 class NamespaceMagics(Magics):
450 vdtype = var.dtype
451 vdtype = var.dtype
451
452
452 if vbytes < 100000:
453 if vbytes < 100000:
453 print aformat % (vshape, vsize, vdtype, vbytes)
454 print(aformat % (vshape, vsize, vdtype, vbytes))
454 else:
455 else:
455 print aformat % (vshape, vsize, vdtype, vbytes),
456 print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
456 if vbytes < Mb:
457 if vbytes < Mb:
457 print '(%s kb)' % (vbytes/kb,)
458 print('(%s kb)' % (vbytes/kb,))
458 else:
459 else:
459 print '(%s Mb)' % (vbytes/Mb,)
460 print('(%s Mb)' % (vbytes/Mb,))
460 else:
461 else:
461 try:
462 try:
462 vstr = str(var)
463 vstr = str(var)
@@ -467,9 +468,9 class NamespaceMagics(Magics):
467 vstr = "<object with id %d (str() failed)>" % id(var)
468 vstr = "<object with id %d (str() failed)>" % id(var)
468 vstr = vstr.replace('\n', '\\n')
469 vstr = vstr.replace('\n', '\\n')
469 if len(vstr) < 50:
470 if len(vstr) < 50:
470 print vstr
471 print(vstr)
471 else:
472 else:
472 print vstr[:25] + "<...>" + vstr[-25:]
473 print(vstr[:25] + "<...>" + vstr[-25:])
473
474
474 @line_magic
475 @line_magic
475 def reset(self, parameter_s=''):
476 def reset(self, parameter_s=''):
@@ -540,7 +541,7 class NamespaceMagics(Magics):
540 except StdinNotImplementedError:
541 except StdinNotImplementedError:
541 ans = True
542 ans = True
542 if not ans:
543 if not ans:
543 print 'Nothing done.'
544 print('Nothing done.')
544 return
545 return
545
546
546 if 's' in opts: # Soft reset
547 if 's' in opts: # Soft reset
@@ -557,11 +558,11 class NamespaceMagics(Magics):
557 for target in args:
558 for target in args:
558 target = target.lower() # make matches case insensitive
559 target = target.lower() # make matches case insensitive
559 if target == 'out':
560 if target == 'out':
560 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
561 print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
561 self.shell.displayhook.flush()
562 self.shell.displayhook.flush()
562
563
563 elif target == 'in':
564 elif target == 'in':
564 print "Flushing input history"
565 print("Flushing input history")
565 pc = self.shell.displayhook.prompt_count + 1
566 pc = self.shell.displayhook.prompt_count + 1
566 for n in range(1, pc):