在Java中调用Python脚本并传递参数可以通过以下几种方式实现:
使用`Runtime.exec`方法
try {String[] arguments = new String[] {"python","path_to_your_python_script.py","arg1","arg2",// ..."argN"};Process process = Runtime.getRuntime().exec(arguments);BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));String line;while ((line = in.readLine()) != null) {System.out.println(line);}process.waitFor();} catch (IOException | InterruptedException e) {e.printStackTrace();}
使用`ProcessBuilder`类
try {ProcessBuilder processBuilder = new ProcessBuilder("python", "path_to_your_python_script.py", "arg1", "arg2", /* ... */);Process process = processBuilder.start();BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));String line;while ((line = in.readLine()) != null) {System.out.println(line);}process.waitFor();} catch (IOException | InterruptedException e) {e.printStackTrace();}
使用`jython`库(不推荐,因为可能不支持所有第三方库):
import org.python.util.PythonInterpreter;public class JavaCallPython {public static void main(String[] args) {try (PythonInterpreter interpreter = new PythonInterpreter()) {interpreter.execfile("path_to_your_python_script.py");interpreter.set("arg1", "value1");interpreter.set("arg2", "value2");// ...interpreter.execfile("path_to_your_python_script.py");}}}
使用`ProcessBuilder`传递参数(适用于Windows和Linux系统):
try {ProcessBuilder processBuilder = new ProcessBuilder("python", "path_to_your_python_script.py", "arg1", "arg2", /* ... */);Process process = processBuilder.start();BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));String line;while ((line = in.readLine()) != null) {System.out.println(line);}process.waitFor();} catch (IOException | InterruptedException e) {e.printStackTrace();}
请确保Python脚本路径正确,参数传递无误。如果有特殊字符或空格,请使用双引号将参数值括起来。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/140255.html