Today I created a little swing GUI shell to provide an interactive session with a Jython interpreter. It comprises two text areas — a larger area at the top for output, and a smaller text area at the bottom for input. It is not line-level interactive, as the normal console shell is; instead, you submit complete expressions with Ctrl-ENTER.

There's a bit of trick in there about two different methods on the PythonInterpreter API: exec and eval. Digging through the sources of the provided interpreters, I came up with the following, which seems to work well:

cmd = input.getText(); output.write( ">>> " + cmd + "\n" ); try { res = interp.eval( cmd ); output.write( res.toString() + "\n" ); } catch ( PyException exec ) { if ( Py.matchException( exec, Py.SyntaxError ) ) { try { interp.exec( cmd ); } catch ( PyException exec2 ) { output.write( exec2.toString() ); //exec2.printStackTrace( new PrintWriter(output) ); } } else { output.write( exec.toString() ); //exec.printStackTrace( new PrintWriter( output ) ); } }

Here is the whole swing jython interpreter shell program; compiled against Jython 2.1,


Published

Category

Posts

Tags

Contact