|
| 1 | +# XXX This is broken with class exceptions |
| 2 | + |
1 | 3 | """Utilities dealing with code objects.""" |
2 | 4 |
|
3 | 5 | def compile_command(source, filename="<input>", symbol="single"): |
@@ -50,3 +52,53 @@ def compile_command(source, filename="<input>", symbol="single"): |
50 | 52 | return code |
51 | 53 | if not code1 and err1 == err2: |
52 | 54 | raise SyntaxError, err1 |
| 55 | + |
| 56 | + |
| 57 | +def interact(banner=None, readfunc=raw_input, local=None): |
| 58 | + # Due to Jeff Epler, with changes by Guido: |
| 59 | + """Closely emulate the interactive Python console.""" |
| 60 | + try: import readline # Enable GNU readline if available |
| 61 | + except: pass |
| 62 | + local = local or {} |
| 63 | + import sys, string, traceback |
| 64 | + sys.ps1 = '>>> ' |
| 65 | + sys.ps2 = '... ' |
| 66 | + if banner: |
| 67 | + print banner |
| 68 | + else: |
| 69 | + print "Python Interactive Console", sys.version |
| 70 | + print sys.copyright |
| 71 | + buf = [] |
| 72 | + while 1: |
| 73 | + if buf: prompt = sys.ps2 |
| 74 | + else: prompt = sys.ps1 |
| 75 | + try: line = readfunc(prompt) |
| 76 | + except KeyboardInterrupt: |
| 77 | + print "\nKeyboardInterrupt" |
| 78 | + buf = [] |
| 79 | + continue |
| 80 | + except EOFError: break |
| 81 | + buf.append(line) |
| 82 | + try: x = compile_command(string.join(buf, "\n")) |
| 83 | + except SyntaxError: |
| 84 | + traceback.print_exc(0) |
| 85 | + buf = [] |
| 86 | + continue |
| 87 | + if x == None: continue |
| 88 | + else: |
| 89 | + try: exec x in local |
| 90 | + except: |
| 91 | + exc_type, exc_value, exc_traceback = \ |
| 92 | + sys.exc_type, sys.exc_value, \ |
| 93 | + sys.exc_traceback |
| 94 | + l = len(traceback.extract_tb(sys.exc_traceback)) |
| 95 | + try: 1/0 |
| 96 | + except: |
| 97 | + m = len(traceback.extract_tb( |
| 98 | + sys.exc_traceback)) |
| 99 | + traceback.print_exception(exc_type, |
| 100 | + exc_value, exc_traceback, l-m) |
| 101 | + buf = [] |
| 102 | + |
| 103 | +if __name__ == '__main__': |
| 104 | + interact() |
0 commit comments