Java可以通过调用外部命令来执行Python脚本,具体方法如下:
- 首先确保Python已经安装并配置好,可以在命令行中输入“python --version”来检查Python是否安装成功。
- 在Java中调用Python脚本,可以使用Java的Runtime类或ProcessBuilder类来执行外部命令。这里以Runtime类为例:
java复制代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CallPythonScript {
public static void main(String[] args) {
String pythonScriptPath = "path/to/your/python/script.py";
String[] command = {"python", pythonScriptPath};
try {
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码中,需要将“path/to/your/python/script.py”替换为实际的Python脚本路径。然后通过Runtime类执行外部命令,并获取Python脚本的输出结果,这里使用了BufferedReader来读取输出结果。
- 如果Python脚本需要传递参数,可以将参数作为命令行参数传递给Java程序,然后再传递给Python脚本。例如:
java复制代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class CallPythonScriptWithArgs {
public static void main(String[] args) {
String pythonScriptPath = "path/to/your/python/script.py";
String arg1 = "arg1";
String arg2 = "arg2";
String[] command = {"python", pythonScriptPath, arg1, arg2};
try {
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码中,将Python脚本路径和两个参数作为命令行参数传递给Java程序,然后再传递给Python脚本。
标签:调用,java,String,python,Python,BufferedReader,import From: https://blog.51cto.com/u_16307208/8042757