ninia / jep

Embed Python in Java
Other
1.27k stars 146 forks source link

jep.JepException: <class 'ImportError'>: math.log #541

Open mwxiaomao opened 4 days ago

mwxiaomao commented 4 days ago

Describe the problem A clear and concise description of what the problem is.

Environment (please complete the following information):

Java code: try (Jep jep = new SubInterpreter()) { jep.eval("import math"); jep.eval("result = math.log(10)"); double result = jep.getValue("result", Double.class); System.out.println("Natural logarithm of 10 is: " + result); } catch (JepException e) { e.printStackTrace(); }

jep.JepException: <class 'ImportError'>: math.log at /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/jep/java_import_hook.getattr(java_import_hook.py:57) at .(:1) at jep.Jep.eval(Native Method) at jep.Jep.eval(Jep.java:326) at com.my.cloud.JepTest.main(JepTest.java:30) Caused by: java.lang.ClassNotFoundException: math.log at java.net.URLClassLoader.findClass(URLClassLoader.java:382) at java.lang.ClassLoader.loadClass(ClassLoader.java:418) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355) at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ... 3 more

ndjensen commented 4 days ago

The java_import_hook and ClassNotFoundException in the stacktrace indicates it's trying to import math.log as if it was a Java class. You presumably have a Java package on your classpath starting with math. Jep uses a ClassEnquirer to decide if it should attempt an import from Java or Python. You will need to implement a custom ClassEnquirer that indicates correctly if the package should be imported from Java or Python. The default ClassEnquirer, ClassList, takes all the Java packages on the classpath and indicates those should be imported from Java, which is why I believe you have a package starting with math on your classpath.

For related issues, discussion, and examples, see #173, #377, #466.

mwxiaomao commented 3 days ago

Thanks