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