java - 使用 Process Builder 从 Java 运行 python

标签 java python beautifulsoup processbuilder

对于我想要扩展的现有 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/

相关文章:

java - 失败: HTTP error code : 400 While postin JSON data to URL

java - Spring:如何在 Spring 配置中注入(inject) ENUM?

python:在后台运行命令

python - opencv python中的特定像素如何透明?

java - 如何在不创建另一个类的情况下创建内部 child ?

java - 将退出按钮转换为重置按钮

python - 在Python中将SRC属性与汤返回隔离

python - 使用 python 3.6.3 使用 beautifulsoup4 抓取多个页面

python - 更新多行可能已过时的表数据

python - 找不到满足lxml新闻-请要求的版本