对于我想要扩展的现有 Java 代码,我需要从 Java 中运行 python 代码。我为此使用流程构建器:
ProcessBuilder pb = new ProcessBuilder("python", "/directorypath/mypython.py");
Process p=pb.start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
虽然代码在命令行中运行得很好,但在 Java 中我收到“我们需要 BeautifulSoup,抱歉”错误。据我了解,这意味着 Java 环境缺少某种库,但代码可以在命令行中完美运行。
我需要发送一些环境变量吗?如果是,是什么以及如何?
我安装了“BeautifulSoup4”并且它是最新的。
最佳答案
不是一个明确的答案,但这在我看来是该进程运行的环境中的一个问题;它可能缺少一些 python
所期望的环境变量找到您的“BeautifulSoup4”扩展。
一个ProcessBuilder
有一个 .environment()
方法返回 Map<String, String>
其键是环境变量,其值是这些变量的值。 请注意,修改此 map 实际上会改变环境!(即您将启动的过程之一)。
尝试打印您的环境并将其与从命令行运行时的环境进行比较。
关于java - 使用 Process Builder 从 Java 运行 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35685056/