I am trying to write inside a JSP/Servlet Java web project, a python-3 Machine Learning code depends on torch and some advanced frameworks.
I tried:
- to use Jython but it did not work because it only works for python 2 programs.
- to use ProcessBuilder and Runtime.getRuntime().exec("pythonFile.py") to execute the python file but nothing worked.
Is there any suggestions on how to write that Python code in the Java project or communicate them?
2 Answers 2
For option #2, you'd need to pass the python executable into the exec method. For example:
Runtime.getRuntime().exec("python pythonFile.py")
Source: https://www.edureka.co/community/358/how-to-execute-a-python-file-with-few-arguments-in-java
1 Comment
Runtime.getRuntime().exec("notepad") or Runtime.getRuntime().exec("notepad test.txt"), in the same way as you give command on terminal/cmd e.g. C:\>notepad or C:\notepad test.txt.There is also GraalPy (https://www.graalvm.org/python), which can be embedded in Java like Jython, but supports Python 3 and also unlike Jython it can run Python native extensions (NumPy and such) and has JIT compiler.
The usage looks like this:
try (Context context = Context.newBuilder("python")
/* Enabling some of these is needed for various standard library modules */
.allowIO(IOAccess.newBuilder()
.allowHostFileAccess(false)
.allowHostSocketAccess(false)
.build())
.build()) {
context.eval("python", "print('Hello from GraalPy!')");
}
See quick-start demo: https://github.com/graalvm/graal-languages-demos/tree/main/graalpy/graalpy-starter
Disclosure: I am one of GraalPy developers
Comments
Explore related questions
See similar questions with these tags.