> V=E1clav Tolar wrote:
>=20
> Hello,
> I would like to get help from you.
> I am using PythonInterpreter object to execute some Python commands=
. If executing command has bad syntax or throwing exception, some jav=
a exception from exec(String) method is thrown.
> Now, what I want to is to determine what KIND of error in python co=
mmad was occured - for example there is SYNTAX ERROR or PYTHON EXCEPT=
ION is thrown.
You can do this by grabbing sys.last_value and sys.last_type.
Example follows:
import org.python.util.*;
import org.python.core.*;
import java.io.*;
import java.util.*;
/**
* Test for exception in executed code by looking at sys.last_value, =
etc.
**/
public class InterpException
{
public static void main( String[] args )
throws Exception
{
PythonInterpreter.initialize(
System.getProperties(),
new Properties(),
args
);
=20
InteractiveInterpreter interp =3D new InteractiveInterpreter(=
); //#Console(); //#
String inputLine =3D "";
String taskText =3D "";
DataInputStream in =3D new DataInputStream( System.in );
boolean more;
String prompt =3D ">>>";
// get 'sys' imported
interp.runsource( "import sys" );
// get reference to 'sys' module
PyString sysName =3D new PyString( "sys" );
PyStringMap locals =3D (PyStringMap) interp.getLocals();
PySystemState sys =3D (PySystemState) locals.get( sysName );
PyObject lastValue;
=20
System.out.print( prompt );
while ((inputLine =3D in.readLine()) !=3D null){
lastValue =3D sys.last_value; // sentinel to check if it =
hasn't changed
if ( taskText.length() > 0 )
{
taskText +=3D "\n";
}
taskText +=3D inputLine;
more =3D interp.runsource( taskText );
if ( more )
{
prompt =3D "...";
}
else
{
taskText =3D "";
prompt =3D ">>>";
}
if ( lastValue !=3D sys.last_value ) // an error occurred=
in this statement
{
System.out.println( "An error of type: " + sys.last_t=
ype + " occurred." );
// use sys.last_traceback and sys.last_value as desir=
ed...
}
=20
System.out.print( prompt );
}
}
}
kb
|