1 package org.python.util; 3 import org.python.core.*; 4 5 7 public class InteractiveInterpreter extends PythonInterpreter { 8 public InteractiveInterpreter() { 9 super(); 10 cflags = new CompilerFlags(); 11 } 12 public InteractiveInterpreter(PyObject locals) { 13 super(locals); 14 cflags = new CompilerFlags(); 15 } 16 17 39 public boolean runsource(String source) { 40 return runsource(source, "<input>", "single"); 41 } 42 43 public boolean runsource(String source, String filename) { 44 return runsource(source, filename, "single"); 45 } 46 47 public boolean runsource(String source, String filename, String symbol) { 48 PyObject code; 49 try { 50 code = Py.compile_command_flags(source, filename, symbol,cflags,true); 51 } catch (PyException exc) { 52 if (Py.matchException(exc, Py.SyntaxError)) { 53 showexception(exc); 55 return false; 56 } else if (Py.matchException(exc, Py.ValueError) || 57 Py.matchException(exc, Py.OverflowError)) { 58 showexception(exc); 60 return false; 61 } else { 62 throw exc; 63 } 64 } 65 if (code == Py.None) 67 return true; 68 runcode(code); 70 return false; 71 } 72 73 84 85 public void runcode(PyObject code) { 87 try { 88 exec(code); 89 } catch (PyException exc) { 90 if (Py.matchException(exc, Py.SystemExit)) throw exc; 91 showexception(exc); 92 } 93 } 94 95 public void showexception(PyException exc) { 96 Py.printException(exc); 99 } 100 101 public void write(String data) { 102 Py.stderr.write(data); 103 } 104 105 public StringBuffer buffer = new StringBuffer (); 106 public String filename="<stdin>"; 107 108 public void resetbuffer() { 109 buffer.setLength(0); 110 } 111 112 116 public void interrupt(ThreadState ts) { 117 TraceFunction breaker = new BreakTraceFunction(); 118 TraceFunction oldTrace = ts.systemState.tracefunc; 119 ts.systemState.tracefunc = breaker; 120 if (ts.frame != null) 121 ts.frame.tracefunc = breaker; 122 ts.systemState.tracefunc = oldTrace; 123 } 125 } 126 127 class BreakTraceFunction extends TraceFunction { 128 private void doBreak() { 129 throw new Error ("Python interrupt"); 130 } 132 133 public TraceFunction traceCall(PyFrame frame) { 134 doBreak(); 135 return null; 136 } 137 138 public TraceFunction traceReturn(PyFrame frame, PyObject ret) { 139 doBreak(); 140 return null; 141 } 142 143 public TraceFunction traceLine(PyFrame frame, int line) { 144 doBreak(); 145 return null; 146 } 147 148 public TraceFunction traceException(PyFrame frame, PyException exc) { 149 doBreak(); 150 return null; 151 } 152 } 153 | Popular Tags |