How to run python in java

2019-08-13 00:27发布

问题:

How to run file*.py* in your Java program without using Jython? For example: I have JButton and I want to run python script when I click on the JButton. What should I put in Action Preformed for the button to run python script without using Jython?

回答1:

You need to have the python interpreter installed in the machine where you want to do that and call this interpreter as an external command from Java.

Look at this question to know more about how perform that call: Execute external program in java

From there:

String[] params = new String [2];
params[0] = PATH2_YOUR_PYTHON_SETUP + "python.exe";
params[1] = PATH2_YOUR_PYTHON_SCRIPT;
Runtime.getRuntime().exec(params);

Additionally, you can use the returned Process object from exec to interact with your script input/output.