【问题标题】:Running python from Java using Process Builder使用 Process Builder 从 Java 运行 python
【发布时间】:2016-02-28 16:23:50
【问题描述】:

对于想要扩展的现有 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 /directorypath/mypython.py "-A 'A Tool for binary' -c 1"ProcessBuilder 不是 shell 解释器!
  • 好的,但是即使我没有这些参数就通过了 [ ProcessBuilder pb = new ProcessBuilder("python", "/directorypath/mypython.py")] ;我再次收到相同的“我们需要 BeautifulSoup,抱歉”错误。我编辑了这个问题。谢谢!

标签: java python beautifulsoup processbuilder


【解决方案1】:

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

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

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

【讨论】:

  • 根据您的建议,我运行 [ProcessBuilder pb=new ProcessBuilder("env");] 并提取了 linux 的所有环境变量,将它们设置为 Map 并使用此地图使用 ProcessBuilder.environment.putAll(Map) 方法设置 ProcessBuilder 环境变量。我仍然收到相同的错误消息,并且 Process.waitfor() 返回值 1。:(
  • 我说要与命令行中的 env 进行比较,而不是来自 JVM 发出的进程
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
相关资源
最近更新 更多