##// END OF EJS Templates
Convert print statements to print function calls...
Thomas Kluyver -
Show More
@@ -7,6 +7,7 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b''
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 b' 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 b' 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 b''
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 b' 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 b''
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 b' 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 b' 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 b''
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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b''
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 b' 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 b' 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 b''
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 b' 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 b''
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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b''
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 b' 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 b' 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 b' 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 b''
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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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 b' 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):
567 for n in range(1, pc):
567 key = '_i'+repr(n)
568 key = '_i'+repr(n)
@@ -585,15 +586,15 b' class NamespaceMagics(Magics):'
585 if isinstance(val,ndarray):
586 if isinstance(val,ndarray):
586 del user_ns[x]
587 del user_ns[x]
587 except ImportError:
588 except ImportError:
588 print "reset array only works if Numpy is available."
589 print("reset array only works if Numpy is available.")
589
590
590 elif target == 'dhist':
591 elif target == 'dhist':
591 print "Flushing directory history"
592 print("Flushing directory history")
592 del user_ns['_dh'][:]
593 del user_ns['_dh'][:]
593
594
594 else:
595 else:
595 print "Don't know how to reset ",
596 print("Don't know how to reset ", end=' ')
596 print target + ", please run `%reset?` for details"
597 print(target + ", please run `%reset?` for details")
597
598
598 gc.collect()
599 gc.collect()
599
600
@@ -670,11 +671,11 b' class NamespaceMagics(Magics):'
670 except StdinNotImplementedError:
671 except StdinNotImplementedError:
671 ans = True
672 ans = True
672 if not ans:
673 if not ans:
673 print 'Nothing done.'
674 print('Nothing done.')
674 return
675 return
675 user_ns = self.shell.user_ns
676 user_ns = self.shell.user_ns
676 if not regex:
677 if not regex:
677 print 'No regex pattern specified. Nothing done.'
678 print('No regex pattern specified. Nothing done.')
678 return
679 return
679 else:
680 else:
680 try:
681 try:
@@ -701,4 +702,4 b' class NamespaceMagics(Magics):'
701 try:
702 try:
702 self.shell.del_var(varname, ('n' in opts))
703 self.shell.del_var(varname, ('n' in opts))
703 except (NameError, ValueError) as e:
704 except (NameError, ValueError) as e:
704 print type(e).__name__ +": "+ str(e)
705 print(type(e).__name__ +": "+ str(e))
@@ -3,6 +3,7 b''
3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
4 builtin.
4 builtin.
5 """
5 """
6 from __future__ import print_function
6 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
7 # Copyright (c) 2012 The IPython Development Team.
8 # Copyright (c) 2012 The IPython Development Team.
8 #
9 #
@@ -107,7 +108,7 b' class OSMagics(Magics):'
107 # for k, v in stored:
108 # for k, v in stored:
108 # atab.append(k, v[0])
109 # atab.append(k, v[0])
109
110
110 print "Total number of aliases:", len(aliases)
111 print("Total number of aliases:", len(aliases))
111 sys.stdout.flush()
112 sys.stdout.flush()
112 return aliases
113 return aliases
113
114
@@ -115,7 +116,7 b' class OSMagics(Magics):'
115 try:
116 try:
116 alias,cmd = par.split(None, 1)
117 alias,cmd = par.split(None, 1)
117 except TypeError:
118 except TypeError:
118 print(oinspect.getdoc(self.alias))
119 print((oinspect.getdoc(self.alias)))
119 return
120 return
120
121
121 try:
122 try:
@@ -137,7 +138,7 b' class OSMagics(Magics):'
137
138
138 stored = self.shell.db.get('stored_aliases', {} )
139 stored = self.shell.db.get('stored_aliases', {} )
139 if aname in stored:
140 if aname in stored:
140 print "Removing %stored alias",aname
141 print("Removing %stored alias",aname)
141 del stored[aname]
142 del stored[aname]
142 self.shell.db['stored_aliases'] = stored
143 self.shell.db['stored_aliases'] = stored
143
144
@@ -284,7 +285,7 b' class OSMagics(Magics):'
284 try:
285 try:
285 ps = self.shell.user_ns['_dh'][nn]
286 ps = self.shell.user_ns['_dh'][nn]
286 except IndexError:
287 except IndexError:
287 print 'The requested directory does not exist in history.'
288 print('The requested directory does not exist in history.')
288 return
289 return
289 else:
290 else:
290 opts = {}
291 opts = {}
@@ -307,7 +308,7 b' class OSMagics(Magics):'
307 ps = fallback
308 ps = fallback
308
309
309 if ps is None:
310 if ps is None:
310 print "No matching entry in directory history"
311 print("No matching entry in directory history")
311 return
312 return
312 else:
313 else:
313 opts = {}
314 opts = {}
@@ -331,7 +332,7 b' class OSMagics(Magics):'
331
332
332 if ps in bkms:
333 if ps in bkms:
333 target = bkms[ps]
334 target = bkms[ps]
334 print '(bookmark:%s) -> %s' % (ps, target)
335 print('(bookmark:%s) -> %s' % (ps, target))
335 ps = target
336 ps = target
336 else:
337 else:
337 if 'b' in opts:
338 if 'b' in opts:
@@ -347,7 +348,7 b' class OSMagics(Magics):'
347 if hasattr(self.shell, 'term_title') and self.shell.term_title:
348 if hasattr(self.shell, 'term_title') and self.shell.term_title:
348 set_term_title('IPython: ' + abbrev_cwd())
349 set_term_title('IPython: ' + abbrev_cwd())
349 except OSError:
350 except OSError:
350 print sys.exc_info()[1]
351 print(sys.exc_info()[1])
351 else:
352 else:
352 cwd = os.getcwdu()
353 cwd = os.getcwdu()
353 dhist = self.shell.user_ns['_dh']
354 dhist = self.shell.user_ns['_dh']
@@ -366,7 +367,7 b' class OSMagics(Magics):'
366 dhist.append(cwd)
367 dhist.append(cwd)
367 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
368 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
368 if not 'q' in opts and self.shell.user_ns['_dh']:
369 if not 'q' in opts and self.shell.user_ns['_dh']:
369 print self.shell.user_ns['_dh'][-1]
370 print(self.shell.user_ns['_dh'][-1])
370
371
371
372
372 @line_magic
373 @line_magic
@@ -399,7 +400,7 b' class OSMagics(Magics):'
399 raise UsageError("%popd on empty stack")
400 raise UsageError("%popd on empty stack")
400 top = self.shell.dir_stack.pop(0)
401 top = self.shell.dir_stack.pop(0)
401 self.cd(top)
402 self.cd(top)
402 print "popd ->",top
403 print("popd ->",top)
403
404
404 @line_magic
405 @line_magic
405 def dirs(self, parameter_s=''):
406 def dirs(self, parameter_s=''):
@@ -441,9 +442,9 b' class OSMagics(Magics):'
441 return
442 return
442 else:
443 else:
443 ini,fin = 0,len(dh)
444 ini,fin = 0,len(dh)
444 print 'Directory history (kept in _dh)'
445 print('Directory history (kept in _dh)')
445 for i in range(ini, fin):
446 for i in range(ini, fin):
446 print "%d: %s" % (i, dh[i])
447 print("%d: %s" % (i, dh[i]))
447
448
448 @skip_doctest
449 @skip_doctest
449 @line_magic
450 @line_magic
@@ -555,7 +556,7 b' class OSMagics(Magics):'
555 split = 'l' in opts
556 split = 'l' in opts
556 out = self.shell.getoutput(cmd, split=split)
557 out = self.shell.getoutput(cmd, split=split)
557 if 'v' in opts:
558 if 'v' in opts:
558 print '%s ==\n%s' % (var, pformat(out))
559 print('%s ==\n%s' % (var, pformat(out)))
559 if var:
560 if var:
560 self.shell.user_ns.update({var:out})
561 self.shell.user_ns.update({var:out})
561 else:
562 else:
@@ -667,9 +668,9 b' class OSMagics(Magics):'
667 else:
668 else:
668 size = 0
669 size = 0
669 fmt = '%-'+str(size)+'s -> %s'
670 fmt = '%-'+str(size)+'s -> %s'
670 print 'Current bookmarks:'
671 print('Current bookmarks:')
671 for bk in bks:
672 for bk in bks:
672 print fmt % (bk, bkms[bk])
673 print(fmt % (bk, bkms[bk]))
673 else:
674 else:
674 if not args:
675 if not args:
675 raise UsageError("%bookmark: You must specify the bookmark name")
676 raise UsageError("%bookmark: You must specify the bookmark name")
@@ -701,7 +702,7 b' class OSMagics(Magics):'
701 try :
702 try :
702 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
703 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
703 except (ValueError, IOError):
704 except (ValueError, IOError):
704 print "Error: no such file, variable, URL, history range or macro"
705 print("Error: no such file, variable, URL, history range or macro")
705 return
706 return
706
707
707 page.page(self.shell.pycolorize(source_to_unicode(cont)))
708 page.page(self.shell.pycolorize(source_to_unicode(cont)))
@@ -727,11 +728,11 b' class OSMagics(Magics):'
727
728
728 if os.path.exists(filename):
729 if os.path.exists(filename):
729 if args.append:
730 if args.append:
730 print "Appending to %s" % filename
731 print("Appending to %s" % filename)
731 else:
732 else:
732 print "Overwriting %s" % filename
733 print("Overwriting %s" % filename)
733 else:
734 else:
734 print "Writing %s" % filename
735 print("Writing %s" % filename)
735
736
736 mode = 'a' if args.append else 'w'
737 mode = 'a' if args.append else 'w'
737 with io.open(filename, mode, encoding='utf-8') as f:
738 with io.open(filename, mode, encoding='utf-8') as f:
@@ -1,5 +1,6 b''
1 """Implementation of magic functions for matplotlib/pylab support.
1 """Implementation of magic functions for matplotlib/pylab support.
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 #
@@ -139,5 +140,5 b' class PylabMagics(Magics):'
139 def _show_matplotlib_backend(self, gui, backend):
140 def _show_matplotlib_backend(self, gui, backend):
140 """show matplotlib message backend message"""
141 """show matplotlib message backend message"""
141 if not gui or gui == 'auto':
142 if not gui or gui == 'auto':
142 print ("Using matplotlib backend: %s" % backend)
143 print(("Using matplotlib backend: %s" % backend))
143
144
@@ -1,4 +1,5 b''
1 """Magic functions for running cells in various scripts."""
1 """Magic functions for running cells in various scripts."""
2 from __future__ import print_function
2 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
3 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
4 #
5 #
@@ -186,7 +187,7 b' class ScriptMagics(Magics):'
186 p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE)
187 p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE)
187 except OSError as e:
188 except OSError as e:
188 if e.errno == errno.ENOENT:
189 if e.errno == errno.ENOENT:
189 print "Couldn't find program: %r" % cmd[0]
190 print("Couldn't find program: %r" % cmd[0])
190 return
191 return
191 else:
192 else:
192 raise
193 raise
@@ -211,20 +212,20 b' class ScriptMagics(Magics):'
211 p.send_signal(signal.SIGINT)
212 p.send_signal(signal.SIGINT)
212 time.sleep(0.1)
213 time.sleep(0.1)
213 if p.poll() is not None:
214 if p.poll() is not None:
214 print "Process is interrupted."
215 print("Process is interrupted.")
215 return
216 return
216 p.terminate()
217 p.terminate()
217 time.sleep(0.1)
218 time.sleep(0.1)
218 if p.poll() is not None:
219 if p.poll() is not None:
219 print "Process is terminated."
220 print("Process is terminated.")
220 return
221 return
221 p.kill()
222 p.kill()
222 print "Process is killed."
223 print("Process is killed.")
223 except OSError:
224 except OSError:
224 pass
225 pass
225 except Exception as e:
226 except Exception as e:
226 print "Error while terminating subprocess (pid=%i): %s" \
227 print("Error while terminating subprocess (pid=%i): %s" \
227 % (p.pid, e)
228 % (p.pid, e))
228 return
229 return
229 out = py3compat.bytes_to_str(out)
230 out = py3compat.bytes_to_str(out)
230 err = py3compat.bytes_to_str(err)
231 err = py3compat.bytes_to_str(err)
@@ -249,7 +250,7 b' class ScriptMagics(Magics):'
249 def killbgscripts(self, _nouse_=''):
250 def killbgscripts(self, _nouse_=''):
250 """Kill all BG processes started by %%script and its family."""
251 """Kill all BG processes started by %%script and its family."""
251 self.kill_bg_processes()
252 self.kill_bg_processes()
252 print "All background processes were killed."
253 print("All background processes were killed.")
253
254
254 def kill_bg_processes(self):
255 def kill_bg_processes(self):
255 """Kill all BG processes which are still running."""
256 """Kill all BG processes which are still running."""
@@ -9,6 +9,7 b' Authors:'
9 * Min RK
9 * Min RK
10
10
11 """
11 """
12 from __future__ import print_function
12
13
13 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008 The IPython Development Team
15 # Copyright (C) 2008 The IPython Development Team
@@ -129,7 +130,7 b' class ProfileLocate(BaseIPythonApplication):'
129 self.profile = self.extra_args[0]
130 self.profile = self.extra_args[0]
130
131
131 def start(self):
132 def start(self):
132 print self.profile_dir.location
133 print(self.profile_dir.location)
133
134
134
135
135 class ProfileList(Application):
136 class ProfileList(Application):
@@ -160,35 +161,35 b' class ProfileList(Application):'
160 def _print_profiles(self, profiles):
161 def _print_profiles(self, profiles):
161 """print list of profiles, indented."""
162 """print list of profiles, indented."""
162 for profile in profiles:
163 for profile in profiles:
163 print ' %s' % profile
164 print(' %s' % profile)
164
165
165 def list_profile_dirs(self):
166 def list_profile_dirs(self):
166 profiles = list_bundled_profiles()
167 profiles = list_bundled_profiles()
167 if profiles:
168 if profiles:
168 print
169 print()
169 print "Available profiles in IPython:"
170 print("Available profiles in IPython:")
170 self._print_profiles(profiles)
171 self._print_profiles(profiles)
171 print
172 print()
172 print " The first request for a bundled profile will copy it"
173 print(" The first request for a bundled profile will copy it")
173 print " into your IPython directory (%s)," % self.ipython_dir
174 print(" into your IPython directory (%s)," % self.ipython_dir)
174 print " where you can customize it."
175 print(" where you can customize it.")
175
176
176 profiles = list_profiles_in(self.ipython_dir)
177 profiles = list_profiles_in(self.ipython_dir)
177 if profiles:
178 if profiles:
178 print
179 print()
179 print "Available profiles in %s:" % self.ipython_dir
180 print("Available profiles in %s:" % self.ipython_dir)
180 self._print_profiles(profiles)
181 self._print_profiles(profiles)
181
182
182 profiles = list_profiles_in(os.getcwdu())
183 profiles = list_profiles_in(os.getcwdu())
183 if profiles:
184 if profiles:
184 print
185 print()
185 print "Available profiles in current directory (%s):" % os.getcwdu()
186 print("Available profiles in current directory (%s):" % os.getcwdu())
186 self._print_profiles(profiles)
187 self._print_profiles(profiles)
187
188
188 print
189 print()
189 print "To use any of the above profiles, start IPython with:"
190 print("To use any of the above profiles, start IPython with:")
190 print " ipython --profile=<name>"
191 print(" ipython --profile=<name>")
191 print
192 print()
192
193
193 def start(self):
194 def start(self):
194 self.list_profile_dirs()
195 self.list_profile_dirs()
@@ -304,8 +305,8 b' class ProfileApp(Application):'
304
305
305 def start(self):
306 def start(self):
306 if self.subapp is None:
307 if self.subapp is None:
307 print "No subcommand specified. Must specify one of: %s"%(self.subcommands.keys())
308 print("No subcommand specified. Must specify one of: %s"%(self.subcommands.keys()))
308 print
309 print()
309 self.print_description()
310 self.print_description()
310 self.print_subcommands()
311 self.print_subcommands()
311 self.exit(1)
312 self.exit(1)
@@ -7,6 +7,7 b' Authors'
7 * Fernando Perez.
7 * Fernando Perez.
8 * Brian Granger
8 * Brian Granger
9 """
9 """
10 from __future__ import print_function
10
11
11 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
12 # Copyright (C) 2009 The IPython Development Team
13 # Copyright (C) 2009 The IPython Development Team
@@ -74,7 +75,7 b' def getfigs(*fig_nums):'
74 for num in fig_nums:
75 for num in fig_nums:
75 f = Gcf.figs.get(num)
76 f = Gcf.figs.get(num)
76 if f is None:
77 if f is None:
77 print('Warning: figure %s not available.' % num)
78 print(('Warning: figure %s not available.' % num))
78 else:
79 else:
79 figs.append(f.canvas.figure)
80 figs.append(f.canvas.figure)
80 return figs
81 return figs
@@ -21,6 +21,7 b' Authors'
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from __future__ import absolute_import
23 from __future__ import absolute_import
24 from __future__ import print_function
24
25
25 import glob
26 import glob
26 import os
27 import os
@@ -248,7 +249,7 b' class InteractiveShellApp(Configurable):'
248 self.log.info("Enabling GUI event loop integration, "
249 self.log.info("Enabling GUI event loop integration, "
249 "eventloop=%s, matplotlib=%s", gui, backend)
250 "eventloop=%s, matplotlib=%s", gui, backend)
250 if key == "auto":
251 if key == "auto":
251 print ("Using matplotlib backend: %s" % backend)
252 print(("Using matplotlib backend: %s" % backend))
252 else:
253 else:
253 gui = r
254 gui = r
254 self.log.info("Enabling GUI event loop integration, "
255 self.log.info("Enabling GUI event loop integration, "
@@ -1,2 +1,3 b''
1 from __future__ import print_function
1 import sys
2 import sys
2 print sys.argv[1:]
3 print(sys.argv[1:])
@@ -12,6 +12,7 b' This script is meant to be called by other parts of the test suite that call it'
12 via %run as if it were executed interactively by the user. As of 2011-05-29,
12 via %run as if it were executed interactively by the user. As of 2011-05-29,
13 test_run.py calls it.
13 test_run.py calls it.
14 """
14 """
15 from __future__ import print_function
15
16
16 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
17 # Module imports
18 # Module imports
@@ -44,4 +45,4 b" if __name__ == '__main__':"
44
45
45 def call_f():
46 def call_f():
46 for func in cache:
47 for func in cache:
47 print 'lowercased:',func().lower()
48 print('lowercased:',func().lower())
@@ -1,5 +1,6 b''
1 """Tests for debugging machinery.
1 """Tests for debugging 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 #
@@ -36,7 +37,7 b' class _FakeInput(object):'
36
37
37 def readline(self):
38 def readline(self):
38 line = next(self.lines)
39 line = next(self.lines)
39 print line
40 print(line)
40 return line+'\n'
41 return line+'\n'
41
42
42 class PdbTestInput(object):
43 class PdbTestInput(object):
@@ -6,6 +6,7 b' Authors'
6 * Fernando Perez
6 * Fernando Perez
7 * Robert Kern
7 * Robert Kern
8 """
8 """
9 from __future__ import print_function
9 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
10 # Copyright (C) 2010-2011 The IPython Development Team
11 # Copyright (C) 2010-2011 The IPython Development Team
11 #
12 #
@@ -497,10 +498,10 b" if __name__ == '__main__':"
497 # real interpreter would instead send it for execution somewhere.
498 # real interpreter would instead send it for execution somewhere.
498 #src = isp.source; raise EOFError # dbg
499 #src = isp.source; raise EOFError # dbg
499 src, raw = isp.source_raw_reset()
500 src, raw = isp.source_raw_reset()
500 print 'Input source was:\n', src
501 print('Input source was:\n', src)
501 print 'Raw source was:\n', raw
502 print('Raw source was:\n', raw)
502 except EOFError:
503 except EOFError:
503 print 'Bye'
504 print('Bye')
504
505
505 # Tests for cell magics support
506 # Tests for cell magics support
506
507
@@ -79,6 +79,7 b' Inheritance diagram:'
79 #*****************************************************************************
79 #*****************************************************************************
80
80
81 from __future__ import unicode_literals
81 from __future__ import unicode_literals
82 from __future__ import print_function
82
83
83 import inspect
84 import inspect
84 import keyword
85 import keyword
@@ -1035,7 +1036,7 b' class VerboseTB(TBTools):'
1035 try:
1036 try:
1036 self.debugger()
1037 self.debugger()
1037 except KeyboardInterrupt:
1038 except KeyboardInterrupt:
1038 print "\nKeyboardInterrupt"
1039 print("\nKeyboardInterrupt")
1039
1040
1040 #----------------------------------------------------------------------------
1041 #----------------------------------------------------------------------------
1041 class FormattedTB(VerboseTB, ListTB):
1042 class FormattedTB(VerboseTB, ListTB):
@@ -1166,7 +1167,7 b' class AutoFormattedTB(FormattedTB):'
1166 try:
1167 try:
1167 self.debugger()
1168 self.debugger()
1168 except KeyboardInterrupt:
1169 except KeyboardInterrupt:
1169 print "\nKeyboardInterrupt"
1170 print("\nKeyboardInterrupt")
1170
1171
1171 def structured_traceback(self, etype=None, value=None, tb=None,
1172 def structured_traceback(self, etype=None, value=None, tb=None,
1172 tb_offset=None, context=5):
1173 tb_offset=None, context=5):
@@ -1240,27 +1241,27 b' if __name__ == "__main__":'
1240 i = f - g
1241 i = f - g
1241 return h / i
1242 return h / i
1242
1243
1243 print ''
1244 print('')
1244 print '*** Before ***'
1245 print('*** Before ***')
1245 try:
1246 try:
1246 print spam(1, (2, 3))
1247 print(spam(1, (2, 3)))
1247 except:
1248 except:
1248 traceback.print_exc()
1249 traceback.print_exc()
1249 print ''
1250 print('')
1250
1251
1251 handler = ColorTB()
1252 handler = ColorTB()
1252 print '*** ColorTB ***'
1253 print('*** ColorTB ***')
1253 try:
1254 try:
1254 print spam(1, (2, 3))
1255 print(spam(1, (2, 3)))
1255 except:
1256 except:
1256 handler(*sys.exc_info())
1257 handler(*sys.exc_info())
1257 print ''
1258 print('')
1258
1259
1259 handler = VerboseTB()
1260 handler = VerboseTB()
1260 print '*** VerboseTB ***'
1261 print('*** VerboseTB ***')
1261 try:
1262 try:
1262 print spam(1, (2, 3))
1263 print(spam(1, (2, 3)))
1263 except:
1264 except:
1264 handler(*sys.exc_info())
1265 handler(*sys.exc_info())
1265 print ''
1266 print('')
1266
1267
@@ -35,6 +35,7 b' To enable the magics below, execute ``%load_ext rmagic``.'
35 {RGET_DOC}
35 {RGET_DOC}
36
36
37 """
37 """
38 from __future__ import print_function
38
39
39 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
40 # Copyright (C) 2012 The IPython Development Team
41 # Copyright (C) 2012 The IPython Development Team
@@ -617,9 +618,9 b' class RMagics(Magics):'
617 ri.set_writeconsole(old_writeconsole)
618 ri.set_writeconsole(old_writeconsole)
618
619
619 except RInterpreterError as e:
620 except RInterpreterError as e:
620 print(e.stdout)
621 print((e.stdout))
621 if not e.stdout.endswith(e.err):
622 if not e.stdout.endswith(e.err):
622 print(e.err)
623 print((e.err))
623 rmtree(tmpd)
624 rmtree(tmpd)
624 return
625 return
625
626
@@ -9,6 +9,7 b' To automatically restore stored variables at startup, add this to your'
9
9
10 c.StoreMagic.autorestore = True
10 c.StoreMagic.autorestore = True
11 """
11 """
12 from __future__ import print_function
12 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
13 # Copyright (c) 2012, The IPython Development Team.
14 # Copyright (c) 2012, The IPython Development Team.
14 #
15 #
@@ -50,8 +51,8 b' def refresh_variables(ip):'
50 try:
51 try:
51 obj = db[key]
52 obj = db[key]
52 except KeyError:
53 except KeyError:
53 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey
54 print("Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey)
54 print "The error was:", sys.exc_info()[0]
55 print("The error was:", sys.exc_info()[0])
55 else:
56 else:
56 #print "restored",justkey,"=",obj #dbg
57 #print "restored",justkey,"=",obj #dbg
57 ip.user_ns[justkey] = obj
58 ip.user_ns[justkey] = obj
@@ -155,7 +156,7 b' class StoreMagics(Magics):'
155 try:
156 try:
156 obj = db['autorestore/' + arg]
157 obj = db['autorestore/' + arg]
157 except KeyError:
158 except KeyError:
158 print "no stored variable %s" % arg
159 print("no stored variable %s" % arg)
159 else:
160 else:
160 ip.user_ns[arg] = obj
161 ip.user_ns[arg] = obj
161 else:
162 else:
@@ -170,13 +171,13 b' class StoreMagics(Magics):'
170 else:
171 else:
171 size = 0
172 size = 0
172
173
173 print 'Stored variables and their in-db values:'
174 print('Stored variables and their in-db values:')
174 fmt = '%-'+str(size)+'s -> %s'
175 fmt = '%-'+str(size)+'s -> %s'
175 get = db.get
176 get = db.get
176 for var in vars:
177 for var in vars:
177 justkey = os.path.basename(var)
178 justkey = os.path.basename(var)
178 # print 30 first characters from every var
179 # print 30 first characters from every var
179 print fmt % (justkey, repr(get(var, '<unavailable>'))[:50])
180 print(fmt % (justkey, repr(get(var, '<unavailable>'))[:50]))
180
181
181 # default action - store the variable
182 # default action - store the variable
182 else:
183 else:
@@ -188,8 +189,8 b' class StoreMagics(Magics):'
188 else:
189 else:
189 fil = open(fnam, 'w')
190 fil = open(fnam, 'w')
190 obj = ip.ev(args[0])
191 obj = ip.ev(args[0])
191 print "Writing '%s' (%s) to file '%s'." % (args[0],
192 print("Writing '%s' (%s) to file '%s'." % (args[0],
192 obj.__class__.__name__, fnam)
193 obj.__class__.__name__, fnam))
193
194
194
195
195 if not isinstance (obj, basestring):
196 if not isinstance (obj, basestring):
@@ -217,22 +218,22 b' class StoreMagics(Magics):'
217 staliases = db.get('stored_aliases',{})
218 staliases = db.get('stored_aliases',{})
218 staliases[name] = cmd
219 staliases[name] = cmd
219 db['stored_aliases'] = staliases
220 db['stored_aliases'] = staliases
220 print "Alias stored: %s (%s)" % (name, cmd)
221 print("Alias stored: %s (%s)" % (name, cmd))
221 return
222 return
222
223
223 else:
224 else:
224 modname = getattr(inspect.getmodule(obj), '__name__', '')
225 modname = getattr(inspect.getmodule(obj), '__name__', '')
225 if modname == '__main__':
226 if modname == '__main__':
226 print textwrap.dedent("""\
227 print(textwrap.dedent("""\
227 Warning:%s is %s
228 Warning:%s is %s
228 Proper storage of interactively declared classes (or instances
229 Proper storage of interactively declared classes (or instances
229 of those classes) is not possible! Only instances
230 of those classes) is not possible! Only instances
230 of classes in real modules on file system can be %%store'd.
231 of classes in real modules on file system can be %%store'd.
231 """ % (args[0], obj) )
232 """ % (args[0], obj) ))
232 return
233 return
233 #pickled = pickle.dumps(obj)
234 #pickled = pickle.dumps(obj)
234 db[ 'autorestore/' + args[0] ] = obj
235 db[ 'autorestore/' + args[0] ] = obj
235 print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__)
236 print("Stored '%s' (%s)" % (args[0], obj.__class__.__name__))
236
237
237
238
238 def load_ipython_extension(ip):
239 def load_ipython_extension(ip):
@@ -31,6 +31,7 b''
31 Decorator module, see http://pypi.python.org/pypi/decorator
31 Decorator module, see http://pypi.python.org/pypi/decorator
32 for the documentation.
32 for the documentation.
33 """
33 """
34 from __future__ import print_function
34
35
35 __version__ = '3.3.3'
36 __version__ = '3.3.3'
36
37
@@ -162,8 +163,8 b' class FunctionMaker(object):'
162 # print >> sys.stderr, 'Compiling %s' % src
163 # print >> sys.stderr, 'Compiling %s' % src
163 exec code in evaldict
164 exec code in evaldict
164 except:
165 except:
165 print >> sys.stderr, 'Error in generated code:'
166 print('Error in generated code:', file=sys.stderr)
166 print >> sys.stderr, src
167 print(src, file=sys.stderr)
167 raise
168 raise
168 func = evaldict[name]
169 func = evaldict[name]
169 if addsource:
170 if addsource:
@@ -38,6 +38,7 b' To find the directory where IPython would like MathJax installed:'
38 $ python -m IPython.external.mathjax -d
38 $ python -m IPython.external.mathjax -d
39
39
40 """
40 """
41 from __future__ import print_function
41
42
42
43
43 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
@@ -86,14 +87,14 b' def prepare_dest(dest, replace=False):'
86
87
87 if os.path.exists(dest):
88 if os.path.exists(dest):
88 if replace:
89 if replace:
89 print "removing existing MathJax at %s" % dest
90 print("removing existing MathJax at %s" % dest)
90 shutil.rmtree(dest)
91 shutil.rmtree(dest)
91 return True
92 return True
92 else:
93 else:
93 mathjax_js = os.path.join(dest, 'MathJax.js')
94 mathjax_js = os.path.join(dest, 'MathJax.js')
94 if not os.path.exists(mathjax_js):
95 if not os.path.exists(mathjax_js):
95 raise IOError("%s exists, but does not contain MathJax.js" % dest)
96 raise IOError("%s exists, but does not contain MathJax.js" % dest)
96 print "%s already exists" % mathjax_js
97 print("%s already exists" % mathjax_js)
97 return False
98 return False
98 else:
99 else:
99 return True
100 return True
@@ -156,7 +157,7 b" def install_mathjax(tag='v2.2', dest=default_dest, replace=False, file=None, ext"
156 try:
157 try:
157 anything_to_do = prepare_dest(dest, replace)
158 anything_to_do = prepare_dest(dest, replace)
158 except OSError as e:
159 except OSError as e:
159 print("ERROR %s, require write access to %s" % (e, dest))
160 print(("ERROR %s, require write access to %s" % (e, dest)))
160 return 1
161 return 1
161 else:
162 else:
162 if not anything_to_do:
163 if not anything_to_do:
@@ -165,11 +166,11 b" def install_mathjax(tag='v2.2', dest=default_dest, replace=False, file=None, ext"
165 if file is None:
166 if file is None:
166 # download mathjax
167 # download mathjax
167 mathjax_url = "https://github.com/mathjax/MathJax/archive/%s.tar.gz" %tag
168 mathjax_url = "https://github.com/mathjax/MathJax/archive/%s.tar.gz" %tag
168 print "Downloading mathjax source from %s" % mathjax_url
169 print("Downloading mathjax source from %s" % mathjax_url)
169 response = urllib2.urlopen(mathjax_url)
170 response = urllib2.urlopen(mathjax_url)
170 file = response.fp
171 file = response.fp
171
172
172 print "Extracting to %s" % dest
173 print("Extracting to %s" % dest)
173 extractor(file, dest)
174 extractor(file, dest)
174 return 0
175 return 0
175
176
@@ -205,7 +206,7 b' def main():'
205 dest = os.path.join(pargs.install_dir, 'mathjax')
206 dest = os.path.join(pargs.install_dir, 'mathjax')
206
207
207 if pargs.print_dest:
208 if pargs.print_dest:
208 print dest
209 print(dest)
209 return
210 return
210
211
211 # remove/replace existing mathjax?
212 # remove/replace existing mathjax?
@@ -5,6 +5,7 b' Authors:'
5
5
6 * Brian Granger
6 * Brian Granger
7 """
7 """
8 from __future__ import print_function
8 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
9 # Copyright (C) 2013 The IPython Development Team
10 # Copyright (C) 2013 The IPython Development Team
10 #
11 #
@@ -628,7 +629,7 b' class NotebookApp(BaseIPythonApplication):'
628 time.sleep(0.1)
629 time.sleep(0.1)
629 info = self.log.info
630 info = self.log.info
630 info('interrupted')
631 info('interrupted')
631 print self.notebook_info()
632 print(self.notebook_info())
632 sys.stdout.write("Shutdown this notebook server (y/[n])? ")
633 sys.stdout.write("Shutdown this notebook server (y/[n])? ")
633 sys.stdout.flush()
634 sys.stdout.flush()
634 r,w,x = select.select([sys.stdin], [], [], 5)
635 r,w,x = select.select([sys.stdin], [], [], 5)
@@ -639,8 +640,8 b' class NotebookApp(BaseIPythonApplication):'
639 ioloop.IOLoop.instance().stop()
640 ioloop.IOLoop.instance().stop()
640 return
641 return
641 else:
642 else:
642 print "No answer for 5s:",
643 print("No answer for 5s:", end=' ')
643 print "resuming operation..."
644 print("resuming operation...")
644 # no answer, or answer is no:
645 # no answer, or answer is no:
645 # set it back to original SIGINT handler
646 # set it back to original SIGINT handler
646 # use IOLoop.add_callback because signal.signal must be called
647 # use IOLoop.add_callback because signal.signal must be called
@@ -652,7 +653,7 b' class NotebookApp(BaseIPythonApplication):'
652 ioloop.IOLoop.instance().stop()
653 ioloop.IOLoop.instance().stop()
653
654
654 def _signal_info(self, sig, frame):
655 def _signal_info(self, sig, frame):
655 print self.notebook_info()
656 print(self.notebook_info())
656
657
657 def init_components(self):
658 def init_components(self):
658 """Check the components submodule, and warn if it's unclean"""
659 """Check the components submodule, and warn if it's unclean"""
@@ -1,5 +1,6 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Tests for the notebook manager."""
2 """Tests for the notebook manager."""
3 from __future__ import print_function
3
4
4 import os
5 import os
5
6
@@ -66,7 +67,7 b' class TestNotebookManager(TestCase):'
66 try:
67 try:
67 os.makedirs(os_path)
68 os.makedirs(os_path)
68 except OSError:
69 except OSError:
69 print "Directory already exists."
70 print("Directory already exists.")
70
71
71 def test_create_notebook_model(self):
72 def test_create_notebook_model(self):
72 with TemporaryDirectory() as td:
73 with TemporaryDirectory() as td:
@@ -21,6 +21,7 b' separate implementation).'
21 An example notebook is provided in our documentation illustrating interactive
21 An example notebook is provided in our documentation illustrating interactive
22 use of the system.
22 use of the system.
23 """
23 """
24 from __future__ import print_function
24
25
25 #*****************************************************************************
26 #*****************************************************************************
26 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
27 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
@@ -190,7 +191,7 b' class BackgroundJobManager(object):'
190 job.num = len(self.all)+1 if self.all else 0
191 job.num = len(self.all)+1 if self.all else 0
191 self.running.append(job)
192 self.running.append(job)
192 self.all[job.num] = job
193 self.all[job.num] = job
193 print 'Starting job # %s in a separate thread.' % job.num
194 print('Starting job # %s in a separate thread.' % job.num)
194 job.start()
195 job.start()
195 return job
196 return job
196
197
@@ -245,10 +246,10 b' class BackgroundJobManager(object):'
245 Return True if the group had any elements."""
246 Return True if the group had any elements."""
246
247
247 if group:
248 if group:
248 print '%s jobs:' % name
249 print('%s jobs:' % name)
249 for job in group:
250 for job in group:
250 print '%s : %s' % (job.num,job)
251 print('%s : %s' % (job.num,job))
251 print
252 print()
252 return True
253 return True
253
254
254 def _group_flush(self,group,name):
255 def _group_flush(self,group,name):
@@ -259,7 +260,7 b' class BackgroundJobManager(object):'
259 njobs = len(group)
260 njobs = len(group)
260 if njobs:
261 if njobs:
261 plural = {1:''}.setdefault(njobs,'s')
262 plural = {1:''}.setdefault(njobs,'s')
262 print 'Flushing %s %s job%s.' % (njobs,name,plural)
263 print('Flushing %s %s job%s.' % (njobs,name,plural))
263 group[:] = []
264 group[:] = []
264 return True
265 return True
265
266
@@ -325,7 +326,7 b' class BackgroundJobManager(object):'
325 fl_comp = self._group_flush(self.completed, 'Completed')
326 fl_comp = self._group_flush(self.completed, 'Completed')
326 fl_dead = self._group_flush(self.dead, 'Dead')
327 fl_dead = self._group_flush(self.dead, 'Dead')
327 if not (fl_comp or fl_dead):
328 if not (fl_comp or fl_dead):
328 print 'No jobs to flush.'
329 print('No jobs to flush.')
329
330
330 def result(self,num):
331 def result(self,num):
331 """result(N) -> return the result of job N."""
332 """result(N) -> return the result of job N."""
@@ -345,9 +346,9 b' class BackgroundJobManager(object):'
345 if job is None:
346 if job is None:
346 self._update_status()
347 self._update_status()
347 for deadjob in self.dead:
348 for deadjob in self.dead:
348 print "Traceback for: %r" % deadjob
349 print("Traceback for: %r" % deadjob)
349 self._traceback(deadjob)
350 self._traceback(deadjob)
350 print
351 print()
351 else:
352 else:
352 self._traceback(job)
353 self._traceback(job)
353
354
@@ -416,7 +417,7 b' class BackgroundJobBase(threading.Thread):'
416 return '<BackgroundJob #%d: %s>' % (self.num, self.strform)
417 return '<BackgroundJob #%d: %s>' % (self.num, self.strform)
417
418
418 def traceback(self):
419 def traceback(self):
419 print self._tb
420 print(self._tb)
420
421
421 def run(self):
422 def run(self):
422 try:
423 try:
@@ -17,6 +17,7 b' Alternatively, you can add a dreload builtin alongside normal reload with::'
17 This code is almost entirely based on knee.py, which is a Python
17 This code is almost entirely based on knee.py, which is a Python
18 re-implementation of hierarchical module import.
18 re-implementation of hierarchical module import.
19 """
19 """
20 from __future__ import print_function
20 #*****************************************************************************
21 #*****************************************************************************
21 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
22 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
22 #
23 #
@@ -167,7 +168,7 b' def import_submodule(mod, subname, fullname):'
167 if fullname in found_now and fullname in sys.modules:
168 if fullname in found_now and fullname in sys.modules:
168 m = sys.modules[fullname]
169 m = sys.modules[fullname]
169 else:
170 else:
170 print 'Reloading', fullname
171 print('Reloading', fullname)
171 found_now[fullname] = 1
172 found_now[fullname] = 1
172 oldm = sys.modules.get(fullname, None)
173 oldm = sys.modules.get(fullname, None)
173
174
@@ -4,6 +4,7 b' They should honor the line number argument, at least.'
4
4
5 Contributions are *very* welcome.
5 Contributions are *very* welcome.
6 """
6 """
7 from __future__ import print_function
7
8
8 import os
9 import os
9 import pipes
10 import pipes
@@ -45,7 +46,7 b' def install_editor(template, wait=False):'
45 if line is None:
46 if line is None:
46 line = 0
47 line = 0
47 cmd = template.format(filename=pipes.quote(filename), line=line)
48 cmd = template.format(filename=pipes.quote(filename), line=line)
48 print ">", cmd
49 print(">", cmd)
49 proc = subprocess.Popen(cmd, shell=True)
50 proc = subprocess.Popen(cmd, shell=True)
50 if wait and proc.wait() != 0:
51 if wait and proc.wait() != 0:
51 raise TryNext()
52 raise TryNext()
@@ -2,6 +2,7 b''
2 """
2 """
3 GLUT Inputhook support functions
3 GLUT Inputhook support functions
4 """
4 """
5 from __future__ import print_function
5
6
6 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
8 # Copyright (C) 2008-2011 The IPython Development Team
@@ -114,7 +115,7 b' def glut_close():'
114 def glut_int_handler(signum, frame):
115 def glut_int_handler(signum, frame):
115 # Catch sigint and print the defautl message
116 # Catch sigint and print the defautl message
116 signal.signal(signal.SIGINT, signal.default_int_handler)
117 signal.signal(signal.SIGINT, signal.default_int_handler)
117 print '\nKeyboardInterrupt'
118 print('\nKeyboardInterrupt')
118 # Need to reprint the prompt at this stage
119 # Need to reprint the prompt at this stage
119
120
120
121
@@ -103,6 +103,7 b' Inheritance diagram:'
103 Portions (c) 2009 by Robert Kern.
103 Portions (c) 2009 by Robert Kern.
104 :license: BSD License.
104 :license: BSD License.
105 """
105 """
106 from __future__ import print_function
106 from contextlib import contextmanager
107 from contextlib import contextmanager
107 import sys
108 import sys
108 import types
109 import types
@@ -784,6 +785,6 b" if __name__ == '__main__':"
784 self.list = ["blub", "blah", self]
785 self.list = ["blub", "blah", self]
785
786
786 def get_foo(self):
787 def get_foo(self):
787 print "foo"
788 print("foo")
788
789
789 pprint(Foo(), verbose=True)
790 pprint(Foo(), verbose=True)
@@ -1,4 +1,5 b''
1 """PostProcessor for serving reveal.js HTML slideshows."""
1 """PostProcessor for serving reveal.js HTML slideshows."""
2 from __future__ import print_function
2 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
3 #Copyright (c) 2013, the IPython Development Team.
4 #Copyright (c) 2013, the IPython Development Team.
4 #
5 #
@@ -92,7 +93,7 b' class ServePostProcessor(PostProcessorBase):'
92 http_server = httpserver.HTTPServer(app)
93 http_server = httpserver.HTTPServer(app)
93 http_server.listen(self.port, address=self.ip)
94 http_server.listen(self.port, address=self.ip)
94 url = "http://%s:%i/%s" % (self.ip, self.port, filename)
95 url = "http://%s:%i/%s" % (self.ip, self.port, filename)
95 print("Serving your slides at %s" % url)
96 print(("Serving your slides at %s" % url))
96 print("Use Control-C to stop this server")
97 print("Use Control-C to stop this server")
97 if self.open_in_browser:
98 if self.open_in_browser:
98 webbrowser.open(url, new=2)
99 webbrowser.open(url, new=2)
@@ -1,6 +1,7 b''
1 """
1 """
2 Contains debug writer.
2 Contains debug writer.
3 """
3 """
4 from __future__ import print_function
4 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
5 #Copyright (c) 2013, the IPython Development Team.
6 #Copyright (c) 2013, the IPython Development Team.
6 #
7 #
@@ -34,9 +35,9 b' class DebugWriter(WriterBase):'
34 """
35 """
35
36
36 if isinstance(resources['outputs'], dict):
37 if isinstance(resources['outputs'], dict):
37 print("outputs extracted from %s" % notebook_name)
38 print(("outputs extracted from %s" % notebook_name))
38 print('-' * 80)
39 print(('-' * 80))
39 pprint(resources['outputs'], indent=2, width=70)
40 pprint(resources['outputs'], indent=2, width=70)
40 else:
41 else:
41 print("no outputs extracted from %s" % notebook_name)
42 print(("no outputs extracted from %s" % notebook_name))
42 print('=' * 80)
43 print(('=' * 80))
@@ -1,3 +1,4 b''
1 from __future__ import print_function
1 #!/usr/bin/env python
2 #!/usr/bin/env python
2 # -*- coding: utf8 -*-
3 # -*- coding: utf8 -*-
3 import argparse
4 import argparse
@@ -79,10 +80,10 b" if __name__ == '__main__':"
79 key=args.key,
80 key=args.key,
80 verbose=args.verbose)
81 verbose=args.verbose)
81 if nerror is 0:
82 if nerror is 0:
82 print u"[Pass]",name
83 print(u"[Pass]",name)
83 else :
84 else :
84 print u"[ ]",name,'(%d)'%(nerror)
85 print(u"[ ]",name,'(%d)'%(nerror))
85 if args.verbose :
86 if args.verbose :
86 print '=================================================='
87 print('==================================================')
87
88
88
89
@@ -9,6 +9,7 b' Authors:'
9 * MinRK
9 * MinRK
10
10
11 """
11 """
12 from __future__ import print_function
12
13
13 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008-2011 The IPython Development Team
15 # Copyright (C) 2008-2011 The IPython Development Team
@@ -595,8 +596,8 b' class IPClusterApp(BaseIPythonApplication):'
595
596
596 def start(self):
597 def start(self):
597 if self.subapp is None:
598 if self.subapp is None:
598 print "No subcommand specified. Must specify one of: %s"%(self.subcommands.keys())
599 print("No subcommand specified. Must specify one of: %s"%(self.subcommands.keys()))
599 print
600 print()
600 self.print_description()
601 self.print_description()
601 self.print_subcommands()
602 self.print_subcommands()
602 self.exit(1)
603 self.exit(1)
@@ -4,6 +4,7 b' Authors:'
4
4
5 * MinRK
5 * MinRK
6 """
6 """
7 from __future__ import print_function
7 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
8 # Copyright (C) 2010-2011 The IPython Development Team
9 # Copyright (C) 2010-2011 The IPython Development Team
9 #
10 #
@@ -738,9 +739,9 b' class Client(HasTraits):'
738 msg_id = parent['msg_id']
739 msg_id = parent['msg_id']
739 if msg_id not in self.outstanding:
740 if msg_id not in self.outstanding:
740 if msg_id in self.history:
741 if msg_id in self.history:
741 print ("got stale result: %s"%msg_id)
742 print(("got stale result: %s"%msg_id))
742 else:
743 else:
743 print ("got unknown result: %s"%msg_id)
744 print(("got unknown result: %s"%msg_id))
744 else:
745 else:
745 self.outstanding.remove(msg_id)
746 self.outstanding.remove(msg_id)
746
747
@@ -774,11 +775,11 b' class Client(HasTraits):'
774 msg_id = parent['msg_id']
775 msg_id = parent['msg_id']
775 if msg_id not in self.outstanding:
776 if msg_id not in self.outstanding:
776 if msg_id in self.history:
777 if msg_id in self.history:
777 print ("got stale result: %s"%msg_id)
778 print(("got stale result: %s"%msg_id))
778 print self.results[msg_id]
779 print(self.results[msg_id])
779 print msg
780 print(msg)
780 else:
781 else:
781 print ("got unknown result: %s"%msg_id)
782 print(("got unknown result: %s"%msg_id))
782 else:
783 else:
783 self.outstanding.remove(msg_id)
784 self.outstanding.remove(msg_id)
784 content = msg['content']
785 content = msg['content']
@@ -26,6 +26,7 b' Usage'
26 {CONFIG_DOC}
26 {CONFIG_DOC}
27
27
28 """
28 """
29 from __future__ import print_function
29
30
30 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
31 # Copyright (C) 2008 The IPython Development Team
32 # Copyright (C) 2008 The IPython Development Team
@@ -251,7 +252,7 b' class ParallelMagics(Magics):'
251 else:
252 else:
252 str_targets = str(targets)
253 str_targets = str(targets)
253 if self.verbose:
254 if self.verbose:
254 print base + " execution on engine(s): %s" % str_targets
255 print(base + " execution on engine(s): %s" % str_targets)
255
256
256 result = self.view.execute(cell, silent=False, block=False)
257 result = self.view.execute(cell, silent=False, block=False)
257 self.last_result = result
258 self.last_result = result
@@ -358,7 +359,7 b' class ParallelMagics(Magics):'
358 self.shell.run_cell = self.pxrun_cell
359 self.shell.run_cell = self.pxrun_cell
359
360
360 self._autopx = True
361 self._autopx = True
361 print "%autopx enabled"
362 print("%autopx enabled")
362
363
363 def _disable_autopx(self):
364 def _disable_autopx(self):
364 """Disable %autopx by restoring the original InteractiveShell.run_cell.
365 """Disable %autopx by restoring the original InteractiveShell.run_cell.
@@ -366,7 +367,7 b' class ParallelMagics(Magics):'
366 if self._autopx:
367 if self._autopx:
367 self.shell.run_cell = self._original_run_cell
368 self.shell.run_cell = self._original_run_cell
368 self._autopx = False
369 self._autopx = False
369 print "%autopx disabled"
370 print("%autopx disabled")
370
371
371 def pxrun_cell(self, raw_cell, store_history=False, silent=False):
372 def pxrun_cell(self, raw_cell, store_history=False, silent=False):
372 """drop-in replacement for InteractiveShell.run_cell.
373 """drop-in replacement for InteractiveShell.run_cell.
@@ -4,6 +4,7 b' Authors:'
4
4
5 * Min RK
5 * Min RK
6 """
6 """
7 from __future__ import print_function
7 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
8 # Copyright (C) 2010-2011 The IPython Development Team
9 # Copyright (C) 2010-2011 The IPython Development Team
9 #
10 #
@@ -482,9 +483,9 b' class DirectView(View):'
482 modules.add(key)
483 modules.add(key)
483 if not quiet:
484 if not quiet:
484 if fromlist:
485 if fromlist:
485 print "importing %s from %s on engine(s)"%(','.join(fromlist), name)
486 print("importing %s from %s on engine(s)"%(','.join(fromlist), name))
486 else:
487 else:
487 print "importing %s on engine(s)"%name
488 print("importing %s on engine(s)"%name)
488 results.append(self.apply_async(remote_import, name, fromlist, level))
489 results.append(self.apply_async(remote_import, name, fromlist, level))
489 # restore override
490 # restore override
490 __builtin__.__import__ = save_import
491 __builtin__.__import__ = save_import
@@ -830,7 +831,7 b' class DirectView(View):'
830 # This is injected into __builtins__.
831 # This is injected into __builtins__.
831 ip = get_ipython()
832 ip = get_ipython()
832 except NameError:
833 except NameError:
833 print "The IPython parallel magics (%px, etc.) only work within IPython."
834 print("The IPython parallel magics (%px, etc.) only work within IPython.")
834 return
835 return
835
836
836 M = ParallelMagics(ip, self, suffix)
837 M = ParallelMagics(ip, self, suffix)
@@ -1,4 +1,5 b''
1 """toplevel setup/teardown for parallel tests."""
1 """toplevel setup/teardown for parallel tests."""
2 from __future__ import print_function
2
3
3 #-------------------------------------------------------------------------------
4 #-------------------------------------------------------------------------------
4 # Copyright (C) 2011 The IPython Development Team
5 # Copyright (C) 2011 The IPython Development Team
@@ -118,15 +119,15 b' def teardown():'
118 try:
119 try:
119 p.stop()
120 p.stop()
120 except Exception as e:
121 except Exception as e:
121 print e
122 print(e)
122 pass
123 pass
123 if p.poll() is None:
124 if p.poll() is None:
124 time.sleep(.25)
125 time.sleep(.25)
125 if p.poll() is None:
126 if p.poll() is None:
126 try:
127 try:
127 print 'cleaning up test process...'
128 print('cleaning up test process...')
128 p.signal(SIGKILL)
129 p.signal(SIGKILL)
129 except:
130 except:
130 print "couldn't shutdown process: ", p
131 print("couldn't shutdown process: ", p)
131 blackhole.close()
132 blackhole.close()
132
133
@@ -51,6 +51,7 b' Authors'
51 - VΓ‘clavΕ milauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
51 - VΓ‘clavΕ milauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
52 - Skipper Seabold, refactoring, cleanups, pure python addition
52 - Skipper Seabold, refactoring, cleanups, pure python addition
53 """
53 """
54 from __future__ import print_function
54
55
55 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
56 # Imports
57 # Imports
@@ -649,7 +650,7 b' class IPythonDirective(Directive):'
649 #print lines
650 #print lines
650 if len(lines)>2:
651 if len(lines)>2:
651 if debug:
652 if debug:
652 print '\n'.join(lines)
653 print('\n'.join(lines))
653 else: #NOTE: this raises some errors, what's it for?
654 else: #NOTE: this raises some errors, what's it for?
654 #print 'INSERTING %d lines'%len(lines)
655 #print 'INSERTING %d lines'%len(lines)
655 self.state_machine.insert_input(
656 self.state_machine.insert_input(
@@ -826,4 +827,4 b" if __name__=='__main__':"
826 if not os.path.isdir('_static'):
827 if not os.path.isdir('_static'):
827 os.mkdir('_static')
828 os.mkdir('_static')
828 test()
829 test()
829 print 'All OK? Check figures in _static/'
830 print('All OK? Check figures in _static/')
@@ -23,6 +23,7 b' Notes'
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 from __future__ import with_statement
25 from __future__ import with_statement
26 from __future__ import print_function
26
27
27 import sys
28 import sys
28 import warnings
29 import warnings
@@ -154,7 +155,7 b' class InteractiveShellEmbed(TerminalInteractiveShell):'
154 self.banner2 = self.old_banner2
155 self.banner2 = self.old_banner2
155
156
156 if self.exit_msg is not None:
157 if self.exit_msg is not None:
157 print self.exit_msg
158 print(self.exit_msg)
158
159
159 def mainloop(self, local_ns=None, module=None, stack_depth=0,
160 def mainloop(self, local_ns=None, module=None, stack_depth=0,
160 display_banner=None, global_ns=None, compile_flags=None):
161 display_banner=None, global_ns=None, compile_flags=None):
@@ -24,6 +24,7 b' Authors'
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 from __future__ import absolute_import
26 from __future__ import absolute_import
27 from __future__ import print_function
27
28
28 import logging
29 import logging
29 import os
30 import os
@@ -196,7 +197,7 b' class LocateIPythonApp(BaseIPythonApplication):'
196 if self.subapp is not None:
197 if self.subapp is not None:
197 return self.subapp.start()
198 return self.subapp.start()
198 else:
199 else:
199 print self.ipython_dir
200 print(self.ipython_dir)
200
201
201
202
202 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
203 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
@@ -344,7 +345,7 b' class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):'
344 if self.display_banner and self.interact:
345 if self.display_banner and self.interact:
345 self.shell.show_banner()
346 self.shell.show_banner()
346 # Make sure there is a space below the banner.
347 # Make sure there is a space below the banner.
347 if self.log_level <= logging.INFO: print
348 if self.log_level <= logging.INFO: print()
348
349
349 def _pylab_changed(self, name, old, new):
350 def _pylab_changed(self, name, old, new):
350 """Replace --pylab='inline' with --pylab='auto'"""
351 """Replace --pylab='inline' with --pylab='auto'"""
@@ -1,6 +1,7 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Nose-based test runner.
2 """Nose-based test runner.
3 """
3 """
4 from __future__ import print_function
4
5
5 from nose.core import main
6 from nose.core import main
6 from nose.plugins.builtin import plugins
7 from nose.plugins.builtin import plugins
@@ -10,8 +11,8 b' from . import ipdoctest'
10 from .ipdoctest import IPDocTestRunner
11 from .ipdoctest import IPDocTestRunner
11
12
12 if __name__ == '__main__':
13 if __name__ == '__main__':
13 print 'WARNING: this code is incomplete!'
14 print('WARNING: this code is incomplete!')
14 print
15 print()
15
16
16 pp = [x() for x in plugins] # activate all builtin plugins first
17 pp = [x() for x in plugins] # activate all builtin plugins first
17 main(testRunner=IPDocTestRunner(),
18 main(testRunner=IPDocTestRunner(),
@@ -2,6 +2,7 b''
2
2
3 This is used by a companion test case.
3 This is used by a companion test case.
4 """
4 """
5 from __future__ import print_function
5
6
6 import gc
7 import gc
7
8
@@ -16,4 +17,4 b" if __name__ == '__main__':"
16 c_refs = gc.get_referrers(c)
17 c_refs = gc.get_referrers(c)
17 ref_ids = map(id,c_refs)
18 ref_ids = map(id,c_refs)
18
19
19 print 'c referrers:',map(type,c_refs)
20 print('c referrers:',map(type,c_refs))
@@ -1,2 +1,3 b''
1 from __future__ import print_function
1 x = 1
2 x = 1
2 print 'x is:',x
3 print('x is:',x)
@@ -1,5 +1,6 b''
1 """Tests for the decorators we've created for IPython.
1 """Tests for the decorators we've created for IPython.
2 """
2 """
3 from __future__ import print_function
3
4
4 # Module imports
5 # Module imports
5 # Std lib
6 # Std lib
@@ -67,9 +68,9 b' def doctest_bad(x,y=1,**k):'
67 >>> 1+1
68 >>> 1+1
68 3
69 3
69 """
70 """
70 print 'x:',x
71 print('x:',x)
71 print 'y:',y
72 print('y:',y)
72 print 'k:',k
73 print('k:',k)
73
74
74
75
75 def call_doctest_bad():
76 def call_doctest_bad():
@@ -117,7 +118,7 b' class FooClass(object):'
117 >>> f = FooClass(3)
118 >>> f = FooClass(3)
118 junk
119 junk
119 """
120 """
120 print 'Making a FooClass.'
121 print('Making a FooClass.')
121 self.x = x
122 self.x = x
122
123
123 @skip_doctest
124 @skip_doctest
@@ -14,6 +14,7 b' Tests for testing.tools'
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import with_statement
16 from __future__ import with_statement
17 from __future__ import print_function
17
18
18 import os
19 import os
19 import unittest
20 import unittest
@@ -73,16 +74,16 b' def test_temp_pyfile():'
73 class TestAssertPrints(unittest.TestCase):
74 class TestAssertPrints(unittest.TestCase):
74 def test_passing(self):
75 def test_passing(self):
75 with tt.AssertPrints("abc"):
76 with tt.AssertPrints("abc"):
76 print "abcd"
77 print("abcd")
77 print "def"
78 print("def")
78 print b"ghi"
79 print(b"ghi")
79
80
80 def test_failing(self):
81 def test_failing(self):
81 def func():
82 def func():
82 with tt.AssertPrints("abc"):
83 with tt.AssertPrints("abc"):
83 print "acd"
84 print("acd")
84 print "def"
85 print("def")
85 print b"ghi"
86 print(b"ghi")
86
87
87 self.assertRaises(AssertionError, func)
88 self.assertRaises(AssertionError, func)
88
89
@@ -31,6 +31,7 b' Older entry points'
31 are the same, except instead of generating tokens, tokeneater is a callback
31 are the same, except instead of generating tokens, tokeneater is a callback
32 function to which the 5 fields described above are passed as 5 arguments,
32 function to which the 5 fields described above are passed as 5 arguments,
33 each time a new token is found."""
33 each time a new token is found."""
34 from __future__ import print_function
34
35
35 __author__ = 'Ka-Ping Yee <ping@lfw.org>'
36 __author__ = 'Ka-Ping Yee <ping@lfw.org>'
36 __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
37 __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
@@ -161,8 +162,8 b' class StopTokenizing(Exception): pass'
161 def printtoken(type, token, srow_scol, erow_ecol, line): # for testing
162 def printtoken(type, token, srow_scol, erow_ecol, line): # for testing
162 srow, scol = srow_scol
163 srow, scol = srow_scol
163 erow, ecol = erow_ecol
164 erow, ecol = erow_ecol
164 print "%d,%d-%d,%d:\t%s\t%s" % \
165 print("%d,%d-%d,%d:\t%s\t%s" % \
165 (srow, scol, erow, ecol, tok_name[type], repr(token))
166 (srow, scol, erow, ecol, tok_name[type], repr(token)))
166
167
167 def tokenize(readline, tokeneater=printtoken):
168 def tokenize(readline, tokeneater=printtoken):
168 """
169 """
@@ -2,6 +2,7 b''
2 """
2 """
3 Utilities for working with stack frames.
3 Utilities for working with stack frames.
4 """
4 """
5 from __future__ import print_function
5
6
6 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
8 # Copyright (C) 2008-2011 The IPython Development Team
@@ -78,8 +79,8 b" def debugx(expr,pre_msg=''):"
78 expr->value pair."""
79 expr->value pair."""
79
80
80 cf = sys._getframe(1)
81 cf = sys._getframe(1)
81 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
82 print('[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
82 eval(expr,cf.f_globals,cf.f_locals))
83 eval(expr,cf.f_globals,cf.f_locals)))
83
84
84
85
85 # deactivate it by uncommenting the following line, which makes it a no-op
86 # deactivate it by uncommenting the following line, which makes it a no-op
@@ -32,6 +32,7 b' Author: Ville Vainio <vivainio@gmail.com>'
32 License: MIT open source license.
32 License: MIT open source license.
33
33
34 """
34 """
35 from __future__ import print_function
35
36
36 from IPython.external.path import path as Path
37 from IPython.external.path import path as Path
37 import os,stat,time
38 import os,stat,time
@@ -138,7 +139,7 b' class PickleShareDB(collections.MutableMapping):'
138 try:
139 try:
139 all.update(self[f])
140 all.update(self[f])
140 except KeyError:
141 except KeyError:
141 print "Corrupt",f,"deleted - hset is not threadsafe!"
142 print("Corrupt",f,"deleted - hset is not threadsafe!")
142 del self[f]
143 del self[f]
143
144
144 self.uncache(f)
145 self.uncache(f)
@@ -280,25 +281,25 b' class PickleShareLink:'
280 def test():
281 def test():
281 db = PickleShareDB('~/testpickleshare')
282 db = PickleShareDB('~/testpickleshare')
282 db.clear()
283 db.clear()
283 print "Should be empty:",db.items()
284 print("Should be empty:",db.items())
284 db['hello'] = 15
285 db['hello'] = 15
285 db['aku ankka'] = [1,2,313]
286 db['aku ankka'] = [1,2,313]
286 db['paths/nest/ok/keyname'] = [1,(5,46)]
287 db['paths/nest/ok/keyname'] = [1,(5,46)]
287 db.hset('hash', 'aku', 12)
288 db.hset('hash', 'aku', 12)
288 db.hset('hash', 'ankka', 313)
289 db.hset('hash', 'ankka', 313)
289 print "12 =",db.hget('hash','aku')
290 print("12 =",db.hget('hash','aku'))
290 print "313 =",db.hget('hash','ankka')
291 print("313 =",db.hget('hash','ankka'))
291 print "all hashed",db.hdict('hash')
292 print("all hashed",db.hdict('hash'))
292 print db.keys()
293 print(db.keys())
293 print db.keys('paths/nest/ok/k*')
294 print(db.keys('paths/nest/ok/k*'))
294 print dict(db) # snapsot of whole db
295 print(dict(db)) # snapsot of whole db
295 db.uncache() # frees memory, causes re-reads later
296 db.uncache() # frees memory, causes re-reads later
296
297
297 # shorthand for accessing deeply nested files
298 # shorthand for accessing deeply nested files
298 lnk = db.getlink('myobjects/test')
299 lnk = db.getlink('myobjects/test')
299 lnk.foo = 2
300 lnk.foo = 2
300 lnk.bar = lnk.foo + 5
301 lnk.bar = lnk.foo + 5
301 print lnk.bar # 7
302 print(lnk.bar) # 7
302
303
303 def stress():
304 def stress():
304 db = PickleShareDB('~/fsdbtest')
305 db = PickleShareDB('~/fsdbtest')
@@ -316,7 +317,7 b' def stress():'
316 db[str(j)] = db.get(str(j), []) + [(i,j,"proc %d" % os.getpid())]
317 db[str(j)] = db.get(str(j), []) + [(i,j,"proc %d" % os.getpid())]
317 db.hset('hash',j, db.hget('hash',j,15) + 1 )
318 db.hset('hash',j, db.hget('hash',j,15) + 1 )
318
319
319 print i,
320 print(i, end=' ')
320 sys.stdout.flush()
321 sys.stdout.flush()
321 if i % 10 == 0:
322 if i % 10 == 0:
322 db.uncache()
323 db.uncache()
@@ -335,7 +336,7 b' def main():'
335 DB = PickleShareDB
336 DB = PickleShareDB
336 import sys
337 import sys
337 if len(sys.argv) < 2:
338 if len(sys.argv) < 2:
338 print usage
339 print(usage)
339 return
340 return
340
341
341 cmd = sys.argv[1]
342 cmd = sys.argv[1]
@@ -355,7 +356,7 b' def main():'
355 elif cmd == 'testwait':
356 elif cmd == 'testwait':
356 db = DB(args[0])
357 db = DB(args[0])
357 db.clear()
358 db.clear()
358 print db.waitget('250')
359 print(db.waitget('250'))
359 elif cmd == 'test':
360 elif cmd == 'test':
360 test()
361 test()
361 stress()
362 stress()
@@ -1,5 +1,6 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for IPython.utils.text"""
2 """Tests for IPython.utils.text"""
3 from __future__ import print_function
3
4
4 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
5 # Copyright (C) 2011 The IPython Development Team
6 # Copyright (C) 2011 The IPython Development Team
@@ -45,11 +46,11 b' def test_columnize_random():'
45 longer_line = max([len(x) for x in out.split('\n')])
46 longer_line = max([len(x) for x in out.split('\n')])
46 longer_element = max(rand_len)
47 longer_element = max(rand_len)
47 if longer_line > displaywidth:
48 if longer_line > displaywidth:
48 print "Columnize displayed something lager than displaywidth : %s " % longer_line
49 print("Columnize displayed something lager than displaywidth : %s " % longer_line)
49 print "longer element : %s " % longer_element
50 print("longer element : %s " % longer_element)
50 print "displaywidth : %s " % displaywidth
51 print("displaywidth : %s " % displaywidth)
51 print "number of element : %s " % nitems
52 print("number of element : %s " % nitems)
52 print "size of each element :\n %s" % rand_len
53 print("size of each element :\n %s" % rand_len)
53 assert False
54 assert False
54
55
55 def test_columnize_medium():
56 def test_columnize_medium():
General Comments 0
You need to be logged in to leave comments. Login now