ScriptException when calling a python script from Java

I am calling python from Java using the ScriptEngine. The python script uses tensorflow and it runs fine if I run the python script directly. When this script is called from Java, the ScriptEngine eval() throws the following exception. It looks like something is not loaded, but am not sure what needs to be done to address it.

I am new to Python and tensorflow, so it may be trivial to fix. Appreciate your help.

javax.script.ScriptException: SyntaxError: mismatched input ‘print’ expecting NAME in pyclasspath/tensorflow/ at line number 288 at column number 58
at org.python.jsr223.PyScriptEngine.scriptException(
at org.python.jsr223.PyScriptEngine.eval(
at org.python.jsr223.PyScriptEngine.eval(

Caused by: Traceback (most recent call last):
File “”, line 5, in
File “pyclasspath/tensorflow/”, line 288
from tensorflow.python.ops.logging_ops import print_v2 as print
SyntaxError: mismatched input ‘print’ expecting NAME

at org.python.core.ParserFacade.fixParseError(
at org.python.core.ParserFacade.parse(
at org.python.core.imp.compileSource(
at org.python.core.imp.compileSource(
at org.python.core.util.importer.getModuleCode(
at org.python.core.util.importer.importer_load_module(
at org.python.core.ClasspathPyImporter.ClasspathPyImporter_load_module(
at org.python.core.ClasspathPyImporter$ClasspathPyImporter_load_module_exposer.__call__(Unknown Source)
at org.python.core.PyBuiltinMethodNarrow.__call__(
at org.python.core.imp.loadFromLoader(
at org.python.core.imp.find_module(
at org.python.core.imp.import_next(
at org.python.core.imp.import_module_level(
at org.python.core.imp.importName(
at org.python.core.ImportFunction.__call__(
at org.python.core.PyObject.__call__(
at org.python.core.__builtin__.__import__(
at org.python.core.imp.importFromAs(
at org.python.core.imp.importFrom(
at org.python.pycode._pyx0.f$0(<script>:49)
at org.python.pycode._pyx0.call_function(<script>)
at org.python.core.Py.runCode(
at org.python.core.__builtin__.eval(
at org.python.core.__builtin__.eval(
at org.python.util.PythonInterpreter.eval(
at org.python.jsr223.PyScriptEngine.eval(
... 25 more

TensorFlow won’t work with Jython, you’ll need to use CPython, but we can easily use CPython from Java with JavaCPP. Here’s some sample code that you can use to get started:

Please let me know if you have any questions though!

Depending on how complex the TensorFlow script is, you might be able to implement it using TF-Java directly and avoid having a Python runtime. The JSR223 script engine is using Jython, which only supports Python 2 and so can’t run most modern Python code.