使用Process Builder从Java运行python

时间:2016-02-28 16:23:51

标签: java python beautifulsoup processbuilder

对于我想要扩展的现有Java代码,我需要从Java中运行python代码。我正在使用Process builder:

   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'安装并且它是最新的。

1 个答案:

答案 0 :(得分:0)

这不是一个明确的答案,但这在我看来是这个过程运行的环境中的一个问题;它可能缺少python期望找到你的" BeautifulSoup4"扩展

ProcessBuilder有一个.environment()方法返回Map<String, String>,其键是环境变量,其值是那些变量&#39;值。 请注意,修改此地图实际上会改变环境!(您将启动的过程之一)。

尝试并打印您的环境,并将其与从命令行运行时的环境进行比较。