Mariam Ahmad
Mariam Ahmad

Reputation: 43

How to write Python 3 code in a Java web code?

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:

  1. to use Jython but it did not work because it only works for python 2 programs.
  2. 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?

Upvotes: 1

Views: 125

Answers (2)

Steves
Steves

Reputation: 3234

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

Upvotes: 0

Curtis
Curtis

Reputation: 558

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

Upvotes: 2

Related Questions