1

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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Correct! The first word in the argument should be the name of the software e.g. 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.
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.