Python在Java中的调用并不是直接运行Python代码,而是通过Java程序调用Python解释器来执行Python脚本。以下是一些在Java中调用Python的技巧:
try { ProcessBuilder pb = new ProcessBuilder("python", "myscript.py"); Process process = pb.start(); // 可以使用process.getInputStream()、process.getOutputStream()和process.getErrorStream()来读取和写入进程的输入/输出/错误流 int exitCode = process.waitFor(); System.out.println("Exit code: " + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } ProcessBuilder pb = new ProcessBuilder("python", "myscript.py", "arg1", "arg2"); try { ProcessBuilder pb = new ProcessBuilder("python", "myscript.py"); Process process = pb.start(); Thread outputThread = new Thread(() -> { try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } }); outputThread.start(); int exitCode = process.waitFor(); outputThread.join(); System.out.println("Exit code: " + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } try { ProcessBuilder pb = new ProcessBuilder("python", "myscript.py"); Process process = pb.start(); Thread errorThread = new Thread(() -> { try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) { String line; while ((line = reader.readLine()) != null) { System.err.println(line); } } catch (IOException e) { e.printStackTrace(); } }); errorThread.start(); int exitCode = process.waitFor(); errorThread.join(); System.out.println("Exit code: " + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); }