在Java中调用Python脚本可以通过以下几种方法:
使用ProcessBuilder类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PythonCaller {
public static void main(String[] args) {
try {
// 设置Python解释器和Python脚本路径
String pythonInterpreter = "python"; // 根据实际情况修改解释器路径
String pythonScript = "/path/to/your/python/script.py"; // 替换为你的Python脚本路径
ProcessBuilder pb = new ProcessBuilder(pythonInterpreter, pythonScript);
Process process = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
使用Runtime.getRuntime()方法
public class Main {
public static void main(String[] args) {
try {
// 设置Python解释器和Python脚本路径
String exe = "python"; // 根据实际情况修改解释器路径
String command = "path/to/your/python/script.py"; // 替换为你的Python脚本路径
String[] cmdArr = {exe, command};
Process process = Runtime.getRuntime().exec(cmdArr);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
使用Jython库(适用于Python 2.x,可能需要额外下载和配置Jython库):
import org.python.util.PythonInterpreter;
public class JythonExample {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("path/to/your/python/script.py"); // 替换为你的Python脚本路径
interpreter.execfile("print('Hello from Python')");
}
}
请确保Python环境已经正确安装,并且Python解释器的路径已经添加到系统的环境变量中,以便Java程序可以找到并执行Python脚本。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/109904.html