Java - 如何使用processbuilder调用python类

时间:2017-08-30 06:46:49

标签: java python processbuilder

如何从java调用和执行python类方法。我当前的java代码可以工作,但只有我写:

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

但我想执行一个类方法,无论if __name__ == '__main__':

我想运行的示例python类方法:

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文件使用pandas和sqlite3,这些都不能用jython实现。

3 个答案:

答案 0 :(得分: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);
        }
    }
}

答案 1 :(得分:1)

您也可以通过JNI直接调用Python lib。这样,您就不会启动新进程,可以在脚本调用之间共享上下文等。

看看这里的样本:

https://github.com/mkopsnc/keplerhacks/tree/master/python

答案 2 :(得分:0)

这是为我工作的Java类。

class PythonFileReader {
private String path;
private String fileName;
private String methodName;

PythonFileReader(String path, String fileName, String methodName) throws Exception {
    this.path = path;
    this.fileName = fileName;
    this.methodName = methodName;
    reader();
}

private void reader() throws Exception {

    StringBuilder input_result = new StringBuilder();
    StringBuilder output_result = new StringBuilder();
    StringBuilder error_result = new StringBuilder();
    String line;

    String module = fileName.substring(0, fileName.lastIndexOf('.'));
    String command = "import " + module + "; " + module + "." + module + "." + methodName;
    List<String> items = Arrays.asList("python", "-c", command);

    ProcessBuilder pb = new ProcessBuilder(items);
    pb.directory(new File(path));
    Process p = pb.start();
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    while ((line = in.readLine()) != null)
        input_result.append("\n").append(line);
    if (input_result.length() > 0)
        System.out.println(fileName + " : " + input_result);

    while ((line = out.readLine()) != null)
        output_result.append(" ").append(line);
    if (output_result.length() > 0)
        System.out.println("Output : " + output_result);

    while ((line = error.readLine()) != null)
        error_result.append(" ").append(line);
    if (error_result.length() > 0)
        System.out.println("Error : " + error_result);
}}

这是您使用此类的方法

public static void main(String[] args) throws Exception {

    String path = "python/path/file";
    String pyFileName = "python_name.py";
    String methodeName = "test('stringInput' , 20)";

    new PythonFileReader(path, pyFileName, methodeName );
}

这是我的python类

class test:

def test(name, count):
    print(name + " - " + str([x for x in range(count)]))