##// END OF EJS Templates
Merge pull request #2100 from Carreau/2to3fixes...
Bussonnier Matthias -
r7844:0369b784 merge
parent child Browse files
Show More
@@ -18,6 +18,7 b' Authors:'
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 from __future__ import print_function
21 22
22 23 import os
23 24 import sys
@@ -159,18 +160,18 b' class CrashHandler(object):'
159 160
160 161 # print traceback to screen
161 162 if self.show_crash_traceback:
162 print >> sys.stderr, traceback
163 print(traceback, file=sys.stderr)
163 164
164 165 # and generate a complete report on disk
165 166 try:
166 167 report = open(report_name,'w')
167 168 except:
168 print >> sys.stderr, 'Could not create crash report on disk.'
169 print('Could not create crash report on disk.', file=sys.stderr)
169 170 return
170 171
171 172 # Inform user on stderr of what happened
172 print >> sys.stderr, '\n'+'*'*70+'\n'
173 print >> sys.stderr, self.message_template.format(**self.info)
173 print('\n'+'*'*70+'\n', file=sys.stderr)
174 print(self.message_template.format(**self.info), file=sys.stderr)
174 175
175 176 # Construct report on disk
176 177 report.write(self.make_report(traceback))
@@ -210,5 +211,5 b' def crash_handler_lite(etype, evalue, tb):'
210 211 else:
211 212 # we are not in a shell, show generic config
212 213 config = "c."
213 print >> sys.stderr, _lite_message_template.format(email=author_email, config=config)
214 print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr)
214 215
@@ -24,6 +24,7 b' http://www.python.org/2.2.3/license.html"""'
24 24 #
25 25 #
26 26 #*****************************************************************************
27 from __future__ import print_function
27 28
28 29 import bdb
29 30 import linecache
@@ -46,7 +47,7 b" if '--pydb' in sys.argv:"
46 47 # better protect against it.
47 48 has_pydb = True
48 49 except ImportError:
49 print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available"
50 print("Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available")
50 51
51 52 if has_pydb:
52 53 from pydb import Pdb as OldPdb
@@ -60,12 +61,12 b' else:'
60 61 # the Tracer constructor.
61 62 def BdbQuit_excepthook(et,ev,tb):
62 63 if et==bdb.BdbQuit:
63 print 'Exiting Debugger.'
64 print('Exiting Debugger.')
64 65 else:
65 66 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
66 67
67 68 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
68 print 'Exiting Debugger.'
69 print('Exiting Debugger.')
69 70
70 71
71 72 class Tracer(object):
@@ -294,7 +295,7 b' class Pdb(OldPdb):'
294 295 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
295 296 context = 3):
296 297 #frame, lineno = frame_lineno
297 print >>io.stdout, self.format_stack_entry(frame_lineno, '', context)
298 print(self.format_stack_entry(frame_lineno, '', context), file=io.stdout)
298 299
299 300 # vds: >>
300 301 frame, lineno = frame_lineno
@@ -434,7 +435,7 b' class Pdb(OldPdb):'
434 435 src.append(line)
435 436 self.lineno = lineno
436 437
437 print >>io.stdout, ''.join(src)
438 print(''.join(src), file=io.stdout)
438 439
439 440 except KeyboardInterrupt:
440 441 pass
@@ -455,7 +456,7 b' class Pdb(OldPdb):'
455 456 else:
456 457 first = max(1, int(x) - 5)
457 458 except:
458 print '*** Error in argument:', `arg`
459 print('*** Error in argument:', repr(arg))
459 460 return
460 461 elif self.lineno is None:
461 462 first = max(1, self.curframe.f_lineno - 5)
@@ -514,12 +515,12 b' class Pdb(OldPdb):'
514 515 #######################################################################
515 516
516 517 if not line:
517 print >>self.stdout, 'End of file'
518 print('End of file', file=self.stdout)
518 519 return 0
519 520 line = line.strip()
520 521 # Don't allow setting breakpoint at a blank line
521 522 if (not line or (line[0] == '#') or
522 523 (line[:3] == '"""') or line[:3] == "'''"):
523 print >>self.stdout, '*** Blank or comment'
524 print('*** Blank or comment', file=self.stdout)
524 525 return 0
525 526 return lineno
@@ -21,6 +21,7 b' Authors:'
21 21 #-----------------------------------------------------------------------------
22 22 # Imports
23 23 #-----------------------------------------------------------------------------
24 from __future__ import print_function
24 25
25 26 import __builtin__
26 27
@@ -179,7 +180,7 b' class DisplayHook(Configurable):'
179 180 # But avoid extraneous empty lines.
180 181 result_repr = '\n' + result_repr
181 182
182 print >>io.stdout, result_repr
183 print(result_repr, file=io.stdout)
183 184
184 185 def update_user_ns(self, result):
185 186 """Update user_ns with various things like _, __, _1, etc."""
@@ -188,7 +189,7 b' class DisplayHook(Configurable):'
188 189 if result is not self.shell.user_ns['_oh']:
189 190 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
190 191 warn('Output cache limit (currently '+
191 `self.cache_size`+' entries) hit.\n'
192 repr(self.cache_size)+' entries) hit.\n'
192 193 'Flushing cache and resetting history counter...\n'
193 194 'The only history variables available will be _,__,___ and _1\n'
194 195 'with the current result.')
@@ -208,7 +209,7 b' class DisplayHook(Configurable):'
208 209 # hackish access to top-level namespace to create _1,_2... dynamically
209 210 to_main = {}
210 211 if self.do_full_cache:
211 new_result = '_'+`self.prompt_count`
212 new_result = '_'+repr(self.prompt_count)
212 213 to_main[new_result] = result
213 214 self.shell.push(to_main, interactive=False)
214 215 self.shell.user_ns['_oh'][self.prompt_count] = result
@@ -243,12 +244,12 b' class DisplayHook(Configurable):'
243 244
244 245 def flush(self):
245 246 if not self.do_full_cache:
246 raise ValueError,"You shouldn't have reached the cache flush "\
247 "if full caching is not enabled!"
247 raise ValueError("You shouldn't have reached the cache flush "
248 "if full caching is not enabled!")
248 249 # delete auto-generated vars from global namespace
249 250
250 251 for n in range(1,self.prompt_count + 1):
251 key = '_'+`n`
252 key = '_'+repr(n)
252 253 try:
253 254 del self.shell.user_ns[key]
254 255 except: pass
@@ -16,6 +16,7 b''
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 from __future__ import print_function
19 20
20 21 import __builtin__ as builtin_mod
21 22 import __future__
@@ -792,8 +793,8 b' class InteractiveShell(SingletonConfigurable):'
792 793
793 794 dp = getattr(self.hooks, name, None)
794 795 if name not in IPython.core.hooks.__all__:
795 print "Warning! Hook '%s' is not one of %s" % \
796 (name, IPython.core.hooks.__all__ )
796 print("Warning! Hook '%s' is not one of %s" % \
797 (name, IPython.core.hooks.__all__ ))
797 798 if not dp:
798 799 dp = IPython.core.hooks.CommandChainDispatcher()
799 800
@@ -901,7 +902,7 b' class InteractiveShell(SingletonConfigurable):'
901 902 def _set_call_pdb(self,val):
902 903
903 904 if val not in (0,1,False,True):
904 raise ValueError,'new call_pdb value must be boolean'
905 raise ValueError('new call_pdb value must be boolean')
905 906
906 907 # store value in instance
907 908 self._call_pdb = val
@@ -1314,7 +1315,7 b' class InteractiveShell(SingletonConfigurable):'
1314 1315 try:
1315 1316 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1316 1317 except:
1317 print ('Could not get variable %s from %s' %
1318 print('Could not get variable %s from %s' %
1318 1319 (name,cf.f_code.co_name))
1319 1320 else:
1320 1321 raise ValueError('variables must be a dict/str/list/tuple')
@@ -1489,7 +1490,7 b' class InteractiveShell(SingletonConfigurable):'
1489 1490 else:
1490 1491 pmethod(info.obj, oname)
1491 1492 else:
1492 print 'Object `%s` not found.' % oname
1493 print('Object `%s` not found.' % oname)
1493 1494 return 'not found' # so callers can take other action
1494 1495
1495 1496 def object_inspect(self, oname, detail_level=0):
@@ -1583,10 +1584,10 b' class InteractiveShell(SingletonConfigurable):'
1583 1584 "The custom exceptions must be given AS A TUPLE."
1584 1585
1585 1586 def dummy_handler(self,etype,value,tb,tb_offset=None):
1586 print '*** Simple custom exception handler ***'
1587 print 'Exception type :',etype
1588 print 'Exception value:',value
1589 print 'Traceback :',tb
1587 print('*** Simple custom exception handler ***')
1588 print('Exception type :',etype)
1589 print('Exception value:',value)
1590 print('Traceback :',tb)
1590 1591 #print 'Source code :','\n'.join(self.buffer)
1591 1592
1592 1593 def validate_stb(stb):
@@ -1627,11 +1628,11 b' class InteractiveShell(SingletonConfigurable):'
1627 1628 except:
1628 1629 # clear custom handler immediately
1629 1630 self.set_custom_exc((), None)
1630 print >> io.stderr, "Custom TB Handler failed, unregistering"
1631 print("Custom TB Handler failed, unregistering", file=io.stderr)
1631 1632 # show the exception in handler first
1632 1633 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1633 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1634 print >> io.stdout, "The original exception:"
1634 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1635 print("The original exception:", file=io.stdout)
1635 1636 stb = self.InteractiveTB.structured_traceback(
1636 1637 (etype,value,tb), tb_offset=tb_offset
1637 1638 )
@@ -1755,7 +1756,7 b' class InteractiveShell(SingletonConfigurable):'
1755 1756 Subclasses may override this method to put the traceback on a different
1756 1757 place, like a side channel.
1757 1758 """
1758 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1759 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1759 1760
1760 1761 def showsyntaxerror(self, filename=None):
1761 1762 """Display the syntax error that just occurred.
@@ -2331,9 +2332,9 b' class InteractiveShell(SingletonConfigurable):'
2331 2332 # plain ascii works better w/ pyreadline, on some machines, so
2332 2333 # we use it and only print uncolored rewrite if we have unicode
2333 2334 rw = str(rw)
2334 print >> io.stdout, rw
2335 print(rw, file=io.stdout)
2335 2336 except UnicodeEncodeError:
2336 print "------> " + cmd
2337 print("------> " + cmd)
2337 2338
2338 2339 #-------------------------------------------------------------------------
2339 2340 # Things related to extracting values/expressions from kernel and user_ns
@@ -2622,17 +2623,17 b' class InteractiveShell(SingletonConfigurable):'
2622 2623 try:
2623 2624 func()
2624 2625 except KeyboardInterrupt:
2625 print >> io.stderr, "\nKeyboardInterrupt"
2626 print("\nKeyboardInterrupt", file=io.stderr)
2626 2627 except Exception:
2627 2628 # register as failing:
2628 2629 self._post_execute[func] = False
2629 2630 self.showtraceback()
2630 print >> io.stderr, '\n'.join([
2631 print('\n'.join([
2631 2632 "post-execution function %r produced an error." % func,
2632 2633 "If this problem persists, you can disable failing post-exec functions with:",
2633 2634 "",
2634 2635 " get_ipython().disable_failing_post_execute = True"
2635 ])
2636 ]), file=io.stderr)
2636 2637
2637 2638 if store_history:
2638 2639 # Write output to the database. Does nothing unless
@@ -2694,7 +2695,7 b' class InteractiveShell(SingletonConfigurable):'
2694 2695
2695 2696 # Flush softspace
2696 2697 if softspace(sys.stdout, 0):
2697 print
2698 print()
2698 2699
2699 2700 except:
2700 2701 # It's possible to have exceptions raised here, typically by
@@ -54,7 +54,7 b' class Logger(object):'
54 54 # logmode is a validated property
55 55 def _set_mode(self,mode):
56 56 if mode not in ['append','backup','global','over','rotate']:
57 raise ValueError,'invalid log mode %s given' % mode
57 raise ValueError('invalid log mode %s given' % mode)
58 58 self._logmode = mode
59 59
60 60 def _get_mode(self):
@@ -117,7 +117,7 b' class Logger(object):'
117 117 for f in old:
118 118 root, ext = os.path.splitext(f)
119 119 num = int(ext[1:-1])+1
120 os.rename(f, root+'.'+`num`.zfill(3)+'~')
120 os.rename(f, root+'.'+repr(num).zfill(3)+'~')
121 121 os.rename(self.logfname, self.logfname+'.001~')
122 122 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
123 123
@@ -131,8 +131,8 b' class Logger(object):'
131 131 """Switch logging on/off. val should be ONLY a boolean."""
132 132
133 133 if val not in [False,True,0,1]:
134 raise ValueError, \
135 'Call switch_log ONLY with a boolean argument, not with:',val
134 raise ValueError('Call switch_log ONLY with a boolean argument, '
135 'not with: %s' % val)
136 136
137 137 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
138 138
@@ -568,7 +568,7 b' class Magics(object):'
568 568
569 569 mode = kw.get('mode','string')
570 570 if mode not in ['string','list']:
571 raise ValueError,'incorrect mode given: %s' % mode
571 raise ValueError('incorrect mode given: %s' % mode)
572 572 # Get options
573 573 list_all = kw.get('list_all',0)
574 574 posix = kw.get('posix', os.name == 'posix')
@@ -254,14 +254,14 b' python-profiler package from non-free.""")'
254 254 dump_file = unquote_filename(dump_file)
255 255 prof.dump_stats(dump_file)
256 256 print '\n*** Profile stats marshalled to file',\
257 `dump_file`+'.',sys_exit
257 repr(dump_file)+'.',sys_exit
258 258 if text_file:
259 259 text_file = unquote_filename(text_file)
260 260 pfile = open(text_file,'w')
261 261 pfile.write(output)
262 262 pfile.close()
263 263 print '\n*** Profile printout saved to text file',\
264 `text_file`+'.',sys_exit
264 repr(text_file)+'.',sys_exit
265 265
266 266 if opts.has_key('r'):
267 267 return stats
@@ -13,6 +13,7 b' reference the name under which an object is being read.'
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 from __future__ import print_function
16 17
17 18 __all__ = ['Inspector','InspectColors']
18 19
@@ -335,11 +336,11 b' class Inspector:'
335 336
336 337 def noinfo(self, msg, oname):
337 338 """Generic message when no information is found."""
338 print 'No %s found' % msg,
339 print('No %s found' % msg, end=' ')
339 340 if oname:
340 print 'for %s' % oname
341 print('for %s' % oname)
341 342 else:
342 print
343 print()
343 344
344 345 def pdef(self, obj, oname=''):
345 346 """Print the definition header for any callable object.
@@ -347,7 +348,7 b' class Inspector:'
347 348 If the object is a class, print the constructor information."""
348 349
349 350 if not callable(obj):
350 print 'Object is not callable.'
351 print('Object is not callable.')
351 352 return
352 353
353 354 header = ''
@@ -362,7 +363,7 b' class Inspector:'
362 363 if output is None:
363 364 self.noinfo('definition header',oname)
364 365 else:
365 print >>io.stdout, header,self.format(output),
366 print(header,self.format(output), end=' ', file=io.stdout)
366 367
367 368 # In Python 3, all classes are new-style, so they all have __init__.
368 369 @skip_doctest_py3
@@ -449,9 +450,9 b' class Inspector:'
449 450 # is defined, as long as the file isn't binary and is actually on the
450 451 # filesystem.
451 452 if ofile.endswith(('.so', '.dll', '.pyd')):
452 print 'File %r is binary, not printing.' % ofile
453 print('File %r is binary, not printing.' % ofile)
453 454 elif not os.path.isfile(ofile):
454 print 'File %r does not exist, not printing.' % ofile
455 print('File %r does not exist, not printing.' % ofile)
455 456 else:
456 457 # Print only text files, not extension binaries. Note that
457 458 # getsourcelines returns lineno with 1-offset and page() uses
@@ -25,6 +25,7 b' rid of that dependency, we could move it there.'
25 25 #-----------------------------------------------------------------------------
26 26 # Imports
27 27 #-----------------------------------------------------------------------------
28 from __future__ import print_function
28 29
29 30 import os
30 31 import re
@@ -57,18 +58,18 b' def page_dumb(strng, start=0, screen_lines=25):'
57 58 out_ln = strng.splitlines()[start:]
58 59 screens = chop(out_ln,screen_lines-1)
59 60 if len(screens) == 1:
60 print >>io.stdout, os.linesep.join(screens[0])
61 print(os.linesep.join(screens[0]), file=io.stdout)
61 62 else:
62 63 last_escape = ""
63 64 for scr in screens[0:-1]:
64 65 hunk = os.linesep.join(scr)
65 print >>io.stdout, last_escape + hunk
66 print(last_escape + hunk, file=io.stdout)
66 67 if not page_more():
67 68 return
68 69 esc_list = esc_re.findall(hunk)
69 70 if len(esc_list) > 0:
70 71 last_escape = esc_list[-1]
71 print >>io.stdout, last_escape + os.linesep.join(screens[-1])
72 print(last_escape + os.linesep.join(screens[-1]), file=io.stdout)
72 73
73 74 def _detect_screen_size(use_curses, screen_lines_def):
74 75 """Attempt to work out the number of lines on the screen.
@@ -163,7 +164,7 b' def page(strng, start=0, screen_lines=0, pager_cmd=None):'
163 164 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
164 165 TERM = os.environ.get('TERM','dumb')
165 166 if TERM in ['dumb','emacs'] and os.name != 'nt':
166 print strng
167 print(strng)
167 168 return
168 169 # chop off the topmost part of the string we don't want to see
169 170 str_lines = strng.splitlines()[start:]
@@ -183,13 +184,13 b' def page(strng, start=0, screen_lines=0, pager_cmd=None):'
183 184 try:
184 185 screen_lines += _detect_screen_size(use_curses, screen_lines_def)
185 186 except (TypeError, UnsupportedOperation):
186 print >>io.stdout, str_toprint
187 print(str_toprint, file=io.stdout)
187 188 return
188 189
189 190 #print 'numlines',numlines,'screenlines',screen_lines # dbg
190 191 if numlines <= screen_lines :
191 192 #print '*** normal print' # dbg
192 print >>io.stdout, str_toprint
193 print(str_toprint, file=io.stdout)
193 194 else:
194 195 # Try to open pager and default to internal one if that fails.
195 196 # All failure modes are tagged as 'retval=1', to match the return
@@ -250,7 +251,7 b' def page_file(fname, start=0, pager_cmd=None):'
250 251 start -= 1
251 252 page(open(fname).read(),start)
252 253 except:
253 print 'Unable to show file',`fname`
254 print('Unable to show file',repr(fname))
254 255
255 256
256 257 def get_pager_cmd(pager_cmd=None):
@@ -325,13 +326,13 b" def snip_print(str,width = 75,print_full = 0,header = ''):"
325 326 page(header+str)
326 327 return 0
327 328
328 print header,
329 print(header, end=' ')
329 330 if len(str) < width:
330 print str
331 print(str)
331 332 snip = 0
332 333 else:
333 334 whalf = int((width -5)/2)
334 print str[:whalf] + ' <...> ' + str[-whalf:]
335 print(str[:whalf] + ' <...> ' + str[-whalf:])
335 336 snip = 1
336 337 if snip and print_full == 2:
337 338 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
@@ -1103,8 +1103,8 b' class FormattedTB(VerboseTB, ListTB):'
1103 1103 len(self.valid_modes)
1104 1104 self.mode = self.valid_modes[new_idx]
1105 1105 elif mode not in self.valid_modes:
1106 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1107 'Valid modes: '+str(self.valid_modes)
1106 raise ValueError('Unrecognized mode in FormattedTB: <'+mode+'>\n'
1107 'Valid modes: '+str(self.valid_modes))
1108 1108 else:
1109 1109 self.mode = mode
1110 1110 # include variable details only in 'Verbose' mode
@@ -1231,7 +1231,7 b' if __name__ == "__main__":'
1231 1231 try:
1232 1232 print spam(1, (2, 3))
1233 1233 except:
1234 apply(handler, sys.exc_info() )
1234 handler(*sys.exc_info())
1235 1235 print ''
1236 1236
1237 1237 handler = VerboseTB()
@@ -1239,6 +1239,6 b' if __name__ == "__main__":'
1239 1239 try:
1240 1240 print spam(1, (2, 3))
1241 1241 except:
1242 apply(handler, sys.exc_info() )
1242 handler(*sys.exc_info())
1243 1243 print ''
1244 1244
@@ -87,6 +87,7 b' Some of the known remaining caveats are:'
87 87
88 88 - C extension modules cannot be reloaded, and so cannot be autoreloaded.
89 89 """
90 from __future__ import print_function
90 91
91 92 skip_doctest = True
92 93
@@ -244,8 +245,8 b' class ModuleReloader(object):'
244 245 if py_filename in self.failed:
245 246 del self.failed[py_filename]
246 247 except:
247 print >> sys.stderr, "[autoreload of %s failed: %s]" % (
248 modname, traceback.format_exc(1))
248 print("[autoreload of %s failed: %s]" % (
249 modname, traceback.format_exc(1)), file=sys.stderr)
249 250 self.failed[py_filename] = pymtime
250 251
251 252 #------------------------------------------------------------------------------
@@ -217,7 +217,7 b' def knownfailureif(fail_condition, msg=None):'
217 217 import nose
218 218 def knownfailer(*args, **kwargs):
219 219 if fail_val():
220 raise KnownFailureTest, msg
220 raise KnownFailureTest(msg)
221 221 else:
222 222 return f(*args, **kwargs)
223 223 return nose.tools.make_decorator(f)(knownfailer)
@@ -608,11 +608,11 b' class spawnb(object):'
608 608
609 609 parent_fd, child_fd = os.openpty()
610 610 if parent_fd < 0 or child_fd < 0:
611 raise ExceptionPexpect, "Error! Could not open pty with os.openpty()."
611 raise ExceptionPexpect("Error! Could not open pty with os.openpty().")
612 612
613 613 pid = os.fork()
614 614 if pid < 0:
615 raise ExceptionPexpect, "Error! Failed os.fork()."
615 raise ExceptionPexpect("Error! Failed os.fork().")
616 616 elif pid == 0:
617 617 # Child.
618 618 os.close(parent_fd)
@@ -655,7 +655,7 b' class spawnb(object):'
655 655 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY);
656 656 if fd >= 0:
657 657 os.close(fd)
658 raise ExceptionPexpect, "Error! Failed to disconnect from controlling tty. It is still possible to open /dev/tty."
658 raise ExceptionPexpect("Error! Failed to disconnect from controlling tty. It is still possible to open /dev/tty.")
659 659 except:
660 660 # Good! We are disconnected from a controlling tty.
661 661 pass
@@ -663,14 +663,14 b' class spawnb(object):'
663 663 # Verify we can open child pty.
664 664 fd = os.open(child_name, os.O_RDWR);
665 665 if fd < 0:
666 raise ExceptionPexpect, "Error! Could not open child pty, " + child_name
666 raise ExceptionPexpect("Error! Could not open child pty, " + child_name)
667 667 else:
668 668 os.close(fd)
669 669
670 670 # Verify we now have a controlling tty.
671 671 fd = os.open("/dev/tty", os.O_WRONLY)
672 672 if fd < 0:
673 raise ExceptionPexpect, "Error! Could not open controlling tty, /dev/tty"
673 raise ExceptionPexpect("Error! Could not open controlling tty, /dev/tty")
674 674 else:
675 675 os.close(fd)
676 676
@@ -13,6 +13,7 b''
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 17
17 18 import bdb
18 19 import os
@@ -59,8 +60,8 b' def get_default_editor():'
59 60 def get_pasted_lines(sentinel, l_input=py3compat.input):
60 61 """ Yield pasted lines until the user enters the given sentinel value.
61 62 """
62 print "Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
63 % sentinel
63 print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
64 % sentinel)
64 65 while True:
65 66 try:
66 67 l = l_input(':')
@@ -69,7 +70,7 b' def get_pasted_lines(sentinel, l_input=py3compat.input):'
69 70 else:
70 71 yield l
71 72 except EOFError:
72 print '<EOF>'
73 print('<EOF>')
73 74 return
74 75
75 76
@@ -153,7 +154,7 b' class TerminalMagics(Magics):'
153 154 if name:
154 155 # If storing it for further editing
155 156 self.shell.user_ns[name] = SList(b.splitlines())
156 print "Block assigned to '%s'" % name
157 print("Block assigned to '%s'" % name)
157 158 else:
158 159 self.shell.user_ns['pasted_block'] = b
159 160 self.shell.run_cell(b)
@@ -170,7 +171,7 b' class TerminalMagics(Magics):'
170 171 raise UsageError(
171 172 "Variable 'pasted_block' is not a string, can't execute")
172 173
173 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
174 print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
174 175 self.shell.run_cell(b)
175 176
176 177 @line_magic
@@ -178,7 +179,7 b' class TerminalMagics(Magics):'
178 179 """Toggle autoindent on/off (if available)."""
179 180
180 181 self.shell.set_autoindent()
181 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
182 print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
182 183
183 184 @skip_doctest
184 185 @line_magic
@@ -375,8 +375,7 b' class BackgroundJobBase(threading.Thread):'
375 375 stat_dead_c = -1
376 376
377 377 def __init__(self):
378 raise NotImplementedError, \
379 "This class can not be instantiated directly."
378 raise NotImplementedError("This class can not be instantiated directly.")
380 379
381 380 def _init(self):
382 381 """Common initialization for all BackgroundJob objects"""
@@ -168,6 +168,7 b" print 'bye!'"
168 168 # the file COPYING, distributed as part of this software.
169 169 #
170 170 #*****************************************************************************
171 from __future__ import print_function
171 172
172 173 import os
173 174 import re
@@ -318,7 +319,7 b' class Demo(object):'
318 319
319 320 if index is None:
320 321 if self.finished:
321 print >>io.stdout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.'
322 print('Demo finished. Use <demo_name>.reset() if you want to rerun it.', file=io.stdout)
322 323 return None
323 324 index = self.block_index
324 325 else:
@@ -387,9 +388,9 b' class Demo(object):'
387 388 if index is None:
388 389 return
389 390
390 print >>io.stdout, self.marquee('<%s> block # %s (%s remaining)' %
391 (self.title,index,self.nblocks-index-1))
392 print >>io.stdout,(self.src_blocks_colored[index])
391 print(self.marquee('<%s> block # %s (%s remaining)' %
392 (self.title,index,self.nblocks-index-1)), file=io.stdout)
393 print((self.src_blocks_colored[index]), file=io.stdout)
393 394 sys.stdout.flush()
394 395
395 396 def show_all(self):
@@ -402,12 +403,12 b' class Demo(object):'
402 403 marquee = self.marquee
403 404 for index,block in enumerate(self.src_blocks_colored):
404 405 if silent[index]:
405 print >>io.stdout, marquee('<%s> SILENT block # %s (%s remaining)' %
406 (title,index,nblocks-index-1))
406 print(marquee('<%s> SILENT block # %s (%s remaining)' %
407 (title,index,nblocks-index-1)), file=io.stdout)
407 408 else:
408 print >>io.stdout, marquee('<%s> block # %s (%s remaining)' %
409 (title,index,nblocks-index-1))
410 print >>io.stdout, block,
409 print(marquee('<%s> block # %s (%s remaining)' %
410 (title,index,nblocks-index-1)), file=io.stdout)
411 print(block, end=' ', file=io.stdout)
411 412 sys.stdout.flush()
412 413
413 414 def run_cell(self,source):
@@ -432,18 +433,18 b' class Demo(object):'
432 433 next_block = self.src_blocks[index]
433 434 self.block_index += 1
434 435 if self._silent[index]:
435 print >>io.stdout, marquee('Executing silent block # %s (%s remaining)' %
436 (index,self.nblocks-index-1))
436 print(marquee('Executing silent block # %s (%s remaining)' %
437 (index,self.nblocks-index-1)), file=io.stdout)
437 438 else:
438 439 self.pre_cmd()
439 440 self.show(index)
440 441 if self.auto_all or self._auto[index]:
441 print >>io.stdout, marquee('output:')
442 print(marquee('output:'), file=io.stdout)
442 443 else:
443 print >>io.stdout, marquee('Press <q> to quit, <Enter> to execute...'),
444 print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ', file=io.stdout)
444 445 ans = raw_input().strip()
445 446 if ans:
446 print >>io.stdout, marquee('Block NOT executed')
447 print(marquee('Block NOT executed'), file=io.stdout)
447 448 return
448 449 try:
449 450 save_argv = sys.argv
@@ -462,9 +463,9 b' class Demo(object):'
462 463 mq1 = self.marquee('END OF DEMO')
463 464 if mq1:
464 465 # avoid spurious print >>io.stdout,s if empty marquees are used
465 print >>io.stdout
466 print >>io.stdout, mq1
467 print >>io.stdout, self.marquee('Use <demo_name>.reset() if you want to rerun it.')
466 print(file=io.stdout)
467 print(mq1, file=io.stdout)
468 print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'), file=io.stdout)
468 469 self.finished = True
469 470
470 471 # These methods are meant to be overridden by subclasses who may wish to
@@ -29,6 +29,7 b' NOTES:'
29 29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
30 30 limitations. This means that it will NOT work under native windows Python.
31 31 """
32 from __future__ import print_function
32 33
33 34 # Stdlib imports
34 35 import optparse
@@ -248,7 +249,7 b' class InteractiveRunner(object):'
248 249 if end_normal:
249 250 if interact:
250 251 c.send('\n')
251 print '<< Starting interactive mode >>',
252 print('<< Starting interactive mode >>', end=' ')
252 253 try:
253 254 c.interact()
254 255 except OSError:
@@ -261,7 +262,7 b' class InteractiveRunner(object):'
261 262 else:
262 263 if interact:
263 264 e="Further interaction is not possible: child process is dead."
264 print >> sys.stderr, e
265 print(e, file=sys.stderr)
265 266
266 267 # Leave the child ready for more input later on, otherwise select just
267 268 # hangs on the second invocation.
@@ -283,7 +284,7 b' class InteractiveRunner(object):'
283 284 opts,args = parser.parse_args(argv)
284 285
285 286 if len(args) != 1:
286 print >> sys.stderr,"You must supply exactly one file to run."
287 print("You must supply exactly one file to run.", file=sys.stderr)
287 288 sys.exit(1)
288 289
289 290 self.run_file(args[0],opts.interact)
@@ -2,6 +2,7 b''
2 2
3 3 Not the most elegant or fine-grained, but it does cover at least the bulk
4 4 functionality."""
5 from __future__ import print_function
5 6
6 7 # Global to make tests extra verbose and help debugging
7 8 VERBOSE = True
@@ -50,10 +51,10 b' class RunnerTestCase(unittest.TestCase):'
50 51 if ol1 != ol2:
51 52 mismatch += 1
52 53 if VERBOSE:
53 print '<<< line %s does not match:' % n
54 print repr(ol1)
55 print repr(ol2)
56 print '>>>'
54 print('<<< line %s does not match:' % n)
55 print(repr(ol1))
56 print(repr(ol2))
57 print('>>>')
57 58 self.assert_(mismatch==0,'Number of mismatched lines: %s' %
58 59 mismatch)
59 60
@@ -1,6 +1,7 b''
1 1 """Test suite for pylab_import_all magic
2 2 Modified from the irunner module but using regex.
3 3 """
4 from __future__ import print_function
4 5
5 6 # Global to make tests extra verbose and help debugging
6 7 VERBOSE = True
@@ -58,10 +59,10 b' class RunnerTestCase(unittest.TestCase):'
58 59 if not re.match(ol1,ol2):
59 60 mismatch += 1
60 61 if VERBOSE:
61 print '<<< line %s does not match:' % n
62 print repr(ol1)
63 print repr(ol2)
64 print '>>>'
62 print('<<< line %s does not match:' % n)
63 print(repr(ol1))
64 print(repr(ol2))
65 print('>>>')
65 66 self.assert_(mismatch==0,'Number of mismatched lines: %s' %
66 67 mismatch)
67 68
@@ -11,6 +11,7 b' Authors:'
11 11 # Distributed under the terms of the BSD License. The full license is in
12 12 # the file COPYING, distributed as part of this software.
13 13 #-------------------------------------------------------------------------------
14 from __future__ import print_function
14 15
15 16 import sys
16 17 import tempfile
@@ -70,13 +71,13 b' def generate_output():'
70 71 import sys
71 72 from IPython.core.display import display, HTML, Math
72 73
73 print "stdout"
74 print >> sys.stderr, "stderr"
74 print("stdout")
75 print("stderr", file=sys.stderr)
75 76
76 77 display(HTML("<b>HTML</b>"))
77 78
78 print "stdout2"
79 print >> sys.stderr, "stderr2"
79 print("stdout2")
80 print("stderr2", file=sys.stderr)
80 81
81 82 display(Math(r"\alpha=\beta"))
82 83
@@ -154,7 +155,7 b' class ClusterTestCase(BaseZMQTestCase):'
154 155 time.sleep(0.1)
155 156 self.client.spin()
156 157 if not f():
157 print "Warning: Awaited condition never arrived"
158 print("Warning: Awaited condition never arrived")
158 159
159 160 def setUp(self):
160 161 BaseZMQTestCase.setUp(self)
@@ -180,4 +181,4 b' class ClusterTestCase(BaseZMQTestCase):'
180 181 # self.context.term()
181 182 # print tempfile.TemporaryFile().fileno(),
182 183 # sys.stdout.flush()
183 No newline at end of file
184
@@ -24,6 +24,7 b' itself from the command line. There are two ways of running this script:'
24 24 #-----------------------------------------------------------------------------
25 25 # Imports
26 26 #-----------------------------------------------------------------------------
27 from __future__ import print_function
27 28
28 29 # Stdlib
29 30 import glob
@@ -423,7 +424,7 b' class IPTester(object):'
423 424
424 425 for pid in self.pids:
425 426 try:
426 print 'Cleaning stale PID:', pid
427 print('Cleaning stale PID:', pid)
427 428 os.kill(pid, signal.SIGKILL)
428 429 except OSError:
429 430 # This is just a best effort, if we fail or the process was
@@ -527,8 +528,8 b' def run_iptestall():'
527 528 t_start = time.time()
528 529 try:
529 530 for (name, runner) in runners:
530 print '*'*70
531 print 'IPython test group:',name
531 print('*'*70)
532 print('IPython test group:',name)
532 533 res = runner.run()
533 534 if res:
534 535 failed.append( (name, runner) )
@@ -539,26 +540,26 b' def run_iptestall():'
539 540 nrunners = len(runners)
540 541 nfail = len(failed)
541 542 # summarize results
542 print
543 print '*'*70
544 print 'Test suite completed for system with the following information:'
545 print report()
546 print 'Ran %s test groups in %.3fs' % (nrunners, t_tests)
547 print
548 print 'Status:'
543 print()
544 print('*'*70)
545 print('Test suite completed for system with the following information:')
546 print(report())
547 print('Ran %s test groups in %.3fs' % (nrunners, t_tests))
548 print()
549 print('Status:')
549 550 if not failed:
550 print 'OK'
551 print('OK')
551 552 else:
552 553 # If anything went wrong, point out what command to rerun manually to
553 554 # see the actual errors and individual summary
554 print 'ERROR - %s out of %s test groups failed.' % (nfail, nrunners)
555 print('ERROR - %s out of %s test groups failed.' % (nfail, nrunners))
555 556 for name, failed_runner in failed:
556 print '-'*40
557 print 'Runner failed:',name
558 print 'You may wish to rerun this one individually, with:'
557 print('-'*40)
558 print('Runner failed:',name)
559 print('You may wish to rerun this one individually, with:')
559 560 failed_call_args = [py3compat.cast_unicode(x) for x in failed_runner.call_args]
560 print u' '.join(failed_call_args)
561 print
561 print(u' '.join(failed_call_args))
562 print()
562 563 # Ensure that our exit code indicates failure
563 564 sys.exit(1)
564 565
@@ -36,7 +36,7 b' def getargspec(obj):'
36 36 elif inspect.ismethod(obj):
37 37 func_obj = obj.im_func
38 38 else:
39 raise TypeError, 'arg is not a Python function'
39 raise TypeError('arg is not a Python function')
40 40 args, varargs, varkw = inspect.getargs(func_obj.func_code)
41 41 return args, varargs, varkw, func_obj.func_defaults
42 42
@@ -28,11 +28,13 b' It shows how to use the built-in keyword, token and tokenize modules to'
28 28 scan Python source code and re-emit it with no changes to its original
29 29 formatting (which is the hard part).
30 30 """
31 from __future__ import print_function
31 32
32 33 __all__ = ['ANSICodeColors','Parser']
33 34
34 35 _scheme_default = 'Linux'
35 36
37
36 38 # Imports
37 39 import StringIO
38 40 import keyword
@@ -283,7 +285,7 b' If no filename is given, or if filename is -, read standard input."""'
283 285 try:
284 286 stream = open(fname)
285 287 except IOError as msg:
286 print >> sys.stderr, msg
288 print(msg, file=sys.stderr)
287 289 sys.exit(1)
288 290
289 291 parser = Parser()
@@ -33,8 +33,8 b' def mutex_opts(dict,ex_op):'
33 33 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
34 34 for op1,op2 in ex_op:
35 35 if op1 in dict and op2 in dict:
36 raise ValueError,'\n*** ERROR in Arguments *** '\
37 'Options '+op1+' and '+op2+' are mutually exclusive.'
36 raise ValueError('\n*** ERROR in Arguments *** '\
37 'Options '+op1+' and '+op2+' are mutually exclusive.')
38 38
39 39
40 40 class EvalDict:
@@ -145,7 +145,7 b' class ColorSchemeTable(dict):'
145 145
146 146 if scheme_list:
147 147 if default_scheme == '':
148 raise ValueError,'you must specify the default color scheme'
148 raise ValueError('you must specify the default color scheme')
149 149 for scheme in scheme_list:
150 150 self.add_scheme(scheme)
151 151 self.set_active_scheme(default_scheme)
@@ -157,7 +157,7 b' class ColorSchemeTable(dict):'
157 157 def add_scheme(self,new_scheme):
158 158 """Add a new color scheme to the table."""
159 159 if not isinstance(new_scheme,ColorScheme):
160 raise ValueError,'ColorSchemeTable only accepts ColorScheme instances'
160 raise ValueError('ColorSchemeTable only accepts ColorScheme instances')
161 161 self[new_scheme.name] = new_scheme
162 162
163 163 def set_active_scheme(self,scheme,case_sensitive=0):
@@ -176,8 +176,8 b' class ColorSchemeTable(dict):'
176 176 try:
177 177 scheme_idx = valid_schemes.index(scheme_test)
178 178 except ValueError:
179 raise ValueError,'Unrecognized color scheme: ' + scheme + \
180 '\nValid schemes: '+str(scheme_names).replace("'', ",'')
179 raise ValueError('Unrecognized color scheme: ' + scheme + \
180 '\nValid schemes: '+str(scheme_names).replace("'', ",''))
181 181 else:
182 182 active = scheme_names[scheme_idx]
183 183 self.active_scheme_name = active
@@ -107,7 +107,7 b' def get_py_filename(name, force_win32=None):'
107 107 if os.path.isfile(name):
108 108 return name
109 109 else:
110 raise IOError,'File `%r` not found.' % name
110 raise IOError('File `%r` not found.' % name)
111 111
112 112
113 113 def filefind(filename, path_dirs=None):
@@ -11,6 +11,7 b''
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 from __future__ import print_function
14 15
15 16 import sys
16 17
@@ -33,7 +34,7 b' def test_tee_simple():'
33 34 chan = StringIO()
34 35 text = 'Hello'
35 36 tee = Tee(chan, channel='stdout')
36 print >> chan, text
37 print(text, file=chan)
37 38 nt.assert_equal(chan.getvalue(), text+"\n")
38 39
39 40
@@ -48,7 +49,7 b' class TeeTestCase(dec.ParametricTestCase):'
48 49 setattr(sys, channel, trap)
49 50
50 51 tee = Tee(chan, channel=channel)
51 print >> chan, text,
52 print(text, end='', file=chan)
52 53 setattr(sys, channel, std_ori)
53 54 trap_val = trap.getvalue()
54 55 nt.assert_equals(chan.getvalue(), text)
@@ -78,8 +79,8 b' def test_capture_output():'
78 79 """capture_output() context works"""
79 80
80 81 with capture_output() as io:
81 print 'hi, stdout'
82 print >> sys.stderr, 'hi, stderr'
82 print('hi, stdout')
83 print('hi, stderr', file=sys.stderr)
83 84
84 85 nt.assert_equals(io.stdout, 'hi, stdout\n')
85 86 nt.assert_equals(io.stderr, 'hi, stderr\n')
@@ -13,6 +13,7 b" Utilities for warnings. Shoudn't we just use the built in warnings module."
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 17
17 18 import sys
18 19
@@ -43,7 +44,7 b' def warn(msg,level=2,exit_val=1):'
43 44 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
44 45 io.stderr.write('%s%s' % (header[level],msg))
45 46 if level == 4:
46 print >> io.stderr,'Exiting.\n'
47 print('Exiting.\n', file=io.stderr)
47 48 sys.exit(exit_val)
48 49
49 50
@@ -5,6 +5,8 b''
5 5 #-----------------------------------------------------------------------------
6 6 # Imports
7 7 #-----------------------------------------------------------------------------
8 from __future__ import print_function
9
8 10 # stdlib
9 11 import cPickle as pickle
10 12 import code
@@ -57,25 +59,25 b' class Console(code.InteractiveConsole):'
57 59 return
58 60 c = omsg.content.code.rstrip()
59 61 if c:
60 print '[IN from %s]' % omsg.parent_header.username
61 print c
62 print('[IN from %s]' % omsg.parent_header.username)
63 print(c)
62 64
63 65 def handle_pyout(self, omsg):
64 66 #print omsg # dbg
65 67 if omsg.parent_header.session == self.session.session:
66 print "%s%s" % (sys.ps3, omsg.content.data)
68 print("%s%s" % (sys.ps3, omsg.content.data))
67 69 else:
68 print '[Out from %s]' % omsg.parent_header.username
69 print omsg.content.data
70 print('[Out from %s]' % omsg.parent_header.username)
71 print(omsg.content.data)
70 72
71 73 def print_pyerr(self, err):
72 print >> sys.stderr, err.etype,':', err.evalue
73 print >> sys.stderr, ''.join(err.traceback)
74 print(err.etype,':', err.evalue, file=sys.stderr)
75 print(''.join(err.traceback), file=sys.stderr)
74 76
75 77 def handle_pyerr(self, omsg):
76 78 if omsg.parent_header.session == self.session.session:
77 79 return
78 print >> sys.stderr, '[ERR from %s]' % omsg.parent_header.username
80 print('[ERR from %s]' % omsg.parent_header.username, file=sys.stderr)
79 81 self.print_pyerr(omsg.content)
80 82
81 83 def handle_stream(self, omsg):
@@ -83,8 +85,8 b' class Console(code.InteractiveConsole):'
83 85 outstream = sys.stdout
84 86 else:
85 87 outstream = sys.stderr
86 print >> outstream, '*ERR*',
87 print >> outstream, omsg.content.data,
88 print('*ERR*', end=' ', file=outstream)
89 print(omsg.content.data, end=' ', file=outstream)
88 90
89 91 def handle_output(self, omsg):
90 92 handler = self.handlers.get(omsg.msg_type, None)
@@ -107,12 +109,12 b' class Console(code.InteractiveConsole):'
107 109 if rep.content.status == 'error':
108 110 self.print_pyerr(rep.content)
109 111 elif rep.content.status == 'aborted':
110 print >> sys.stderr, "ERROR: ABORTED"
112 print("ERROR: ABORTED", file=sys.stderr)
111 113 ab = self.messages[rep.parent_header.msg_id].content
112 114 if 'code' in ab:
113 print >> sys.stderr, ab.code
115 print(ab.code, file=sys.stderr)
114 116 else:
115 print >> sys.stderr, ab
117 print(ab, file=sys.stderr)
116 118
117 119 def recv_reply(self):
118 120 ident,rep = self.session.recv(self.request_socket)
@@ -153,7 +155,7 b' class Console(code.InteractiveConsole):'
153 155 time.sleep(0.05)
154 156 else:
155 157 # We exited without hearing back from the kernel!
156 print >> sys.stderr, 'ERROR!!! kernel never got back to us!!!'
158 print('ERROR!!! kernel never got back to us!!!', file=sys.stderr)
157 159
158 160
159 161 class InteractiveClient(object):
@@ -6,6 +6,7 b' use from bintree_script.py'
6 6 Provides parallel [all]reduce functionality
7 7
8 8 """
9 from __future__ import print_function
9 10
10 11 import cPickle as pickle
11 12 import re
@@ -92,7 +93,7 b' def depth(n, tree):'
92 93 def print_bintree(tree, indent=' '):
93 94 """print a binary tree"""
94 95 for n in sorted(tree.keys()):
95 print "%s%s" % (indent * depth(n,tree), n)
96 print("%s%s" % (indent * depth(n,tree), n))
96 97
97 98 #----------------------------------------------------------------------------
98 99 # Communicator class for a binary-tree map
@@ -270,6 +270,8 b" if 'setuptools' in sys.modules:"
270 270 # anything.
271 271 setuptools_extra_args['use_2to3_exclude_fixers'] = [
272 272 'lib2to3.fixes.fix_except',
273 'lib2to3.fixes.fix_apply',
274 'lib2to3.fixes.fix_repr',
273 275 ]
274 276 from setuptools.command.build_py import build_py
275 277 setup_args['cmdclass'] = {'build_py': record_commit_info('IPython', build_cmd=build_py)}
General Comments 0
You need to be logged in to leave comments. Login now