How to Call the Python Method From Java

Complex applications typically are split into multiple modules, as a good software engineering practice. Sometimes those modules are implemented by different people and even on different programming languages; in those cases you need mechanisms to transfer control from code written in one language to code written in another language. In particular, you can call a method written in Python from Java code by launching the Python interpreter parameterized with the name of the method you need to run.

Instructions

    • 1

      Include the following line at the beginning of your Java code:

      import java.io.*;

    • 2

      Build a Java string including the name of the Python method you want to run as in the following sample code:

      String argsToPythonInterpreter = "payroll";

    • 3

      Transfer control to the Python interpreter from the Java program, while instructing the interpreter to call the designated method:

      Runtime rt = Runtime.getRuntime();

      Process pr = rt.exec("python -m "+argsToPythonInterpreter);

      pr.waitFor();

Related Searches:

References

Comments

Related Ads

Featured