2017-08-30 44 views
0

如何從java調用和執行python類方法。我當前的Java代碼的工作,但只有當我寫:Java - 如何使用processbuilder調用python類

if __name__ == '__main__': 
    print("hello") 

但我想執行一個類的方法,不管if __name__ == '__main__':

例蟒蛇類的方法,我想運行:

class SECFileScraper: 
    def __init__(self): 
     self.counter = 5 

    def tester_func(self): 
     return "hello, this test works" 

本質上我想在java中運行SECFileScraper.tester_func()。

我的Java代碼:

try { 

      ProcessBuilder pb = new ProcessBuilder(Arrays.asList(
        "python", pdfFileScraper)); 
      Process p = pb.start(); 

      BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream())); 
      String line = ""; 
      System.out.println("Running Python starts: " + line); 
      int exitCode = p.waitFor(); 
      System.out.println("Exit Code : " + exitCode); 
      line = bfr.readLine(); 
      System.out.println("First Line: " + line); 
      while ((line = bfr.readLine()) != null) { 
       System.out.println("Python Output: " + line); 


      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

pdfFileScraper是文件路徑到我的Python腳本。

我試過jython,但我的python文件使用熊貓和sqlite3,它不能用jython實現。

回答

1

所以如果我理解你的要求,你想調用pdfFileScraper.py中的類方法。從shell這樣做的基礎將是一個類似於:

scraper=path/to/pdfFileScraper.py 
dir_of_scraper=$(dirname $scraper) 
export PYTHONPATH=$dir_of_scraper 
python -c 'import pdfFileScraper; pdfFileScraper.ClassInScraper()' 

,我們要做的就是讓pdfFileScraper的目錄,並把它添加到PYTHONPATH,那麼我們運行python與進口pdfFileScraper文件的命令作爲一個模塊,它公開名稱空間pdfFileScraper中類中的所有方法和類,然後構造一個類ClassInScraper()

在java中,像:

import java.io.*; 
import java.util.*; 

public class RunFile { 
    public static void main(String args[]) throws Exception { 
     File f = new File(args[0]); // .py file (e.g. bob/script.py) 

     String dir = f.getParent(); // dir of .py file 
     String file = f.getName(); // name of .py file (script.py) 
     String module = file.substring(0, file.lastIndexOf('.')); 
     String command = "import " + module + "; " + module + "." + args[1]; 
     List<String> items = Arrays.asList("python", "-c", command); 
     ProcessBuilder pb = new ProcessBuilder(items); 
     Map<String, String> env = pb.environment(); 
     env.put("PYTHONPATH", dir); 
     pb.redirectErrorStream(); 
     Process p = pb.start(); 

     BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     String line = ""; 
     System.out.println("Running Python starts: " + line); 
     int exitCode = p.waitFor(); 
     System.out.println("Exit Code : " + exitCode); 
     line = bfr.readLine(); 
     System.out.println("First Line: " + line); 
     while ((line = bfr.readLine()) != null) { 
      System.out.println("Python Output: " + line); 
     } 
    } 
} 
+0

它沒有做任何輸出。所有我得到的是:'運行Python啓動: 退出代碼:0 第一行:null' – Theo

+2

ProcessBuilder只能處理* printed *返回輸出,所以返回字符串的行實際上不會顯示任何可以解析的東西。你需要「打印」這個測試工作「'來獲得所需的結果。如果你想直接與python對象交互,那麼你將不得不使用像mko這樣的解決方案 - 即在虛擬機中加載一個python解釋器並直接與它交互。 – Petesh