2017-08-30 43 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