java怎么调用python脚本

48次阅读
没有评论

共计 1534 个字符,预计需要花费 4 分钟才能阅读完成。

在 Java 中调用 Python 脚本有多种方法,下面介绍两种常用的方法:

  1. 使用 ProcessBuilder 类:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {public static void main(String[] args) throws IOException {ProcessBuilder pb = new ProcessBuilder("python", "path/to/your/python/script.py");
        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;
        try {exitCode = process.waitFor();
        } catch (InterruptedException e) {e.printStackTrace();
        }

        System.out.println("Python script exited with code: " + exitCode);
    }
}

这种方法通过创建一个 ProcessBuilder 对象来执行 Python 脚本,并读取 Python 脚本输出的结果。可以使用 ProcessBuilderstart()方法来启动 Python 脚本,并使用 getInputStream() 方法获取脚本输出的结果。

  1. 使用 Runtime 类:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {public static void main(String[] args) throws IOException {String command = "python path/to/your/python/script.py";
        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);
        }

        int exitCode;
        try {exitCode = process.waitFor();
        } catch (InterruptedException e) {e.printStackTrace();
        }

        System.out.println("Python script exited with code: " + exitCode);
    }
}

这种方法通过调用 Runtime 类的 exec() 方法来执行 Python 脚本,并读取 Python 脚本输出的结果。可以将要执行的 Python 命令传递给 exec() 方法,并使用 getInputStream() 方法获取脚本输出的结果。

无论使用哪种方法,都可以通过读取 Python 脚本的输出来获取结果,并可以使用 waitFor() 方法等待脚本执行完毕,获取脚本的退出码。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-12发表,共计1534字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)