2016-02-28 77 views
0

對於我想要擴展的現有Java代碼,我需要從Java中運行python代碼。我使用的進程生成此:使用Process Builder從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'並且它是最新的。

+0

您確定該命令的最後一個參數嗎?它看起來很奇怪 – fge

+0

它們只是一些要傳遞的參數。此代碼在命令行上正常工作。 – Varda

+0

是的,但我相信你錯過了他們;除非你的命令行_does_看起來像'python /directorypath/mypython.py「-A'二進制工具'-c 1」'。一個'ProcessBuilder'不是一個shell解釋器! – fge

回答

0

不是一個明確的答案,但這在我看來是一個問題,在這個過程運行的環境中;它可能會丟失一些環境變量,python可能會找到您的「BeautifulSoup4」擴展名。

A ProcessBuilder有一個.environment()方法返回Map<String, String>其關鍵是環境變量,其值是這些變量的值。 請注意,修改此地圖實際上會改變環境!(您將啓動的過程之一)。

嘗試並打印您的環境,並將它與從命令行運行時的情況進行比較。

+0

根據您的建議,我運行了[ProcessBuilder pb = new ProcessBuilder(「env」);]並提取了linux的所有環境變量,將它們設置爲Map ,並使用此映射設置ProcessBuilder環境變量ProcessBuilder.environment.putAll(Map )方法。我仍然得到相同的錯誤消息,並且Process.waitfor()返回值1. :( – Varda

+0

我說你要比較命令行中的env,而不是來自JVM發出的進程 – fge