Java - 如何使用 processbuilder 调用 python 类

Java - How to call python classes using processbuilder

如何从 java 调用和执行 python class 方法。我当前的 java 代码有效,但前提是我写:

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

但是我想执行一个class方法,不管if __name__ == '__main__':

示例python class方法我想运行:

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

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

本质上我想 运行 SECFileScraper.tester_func() 在 java.

我的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无法实现。

因此,如果我理解您的要求,您希望在 pdfFileScraper.py 中调用 class 方法。从 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中class中的所有方法和classes,然后构造一个classClassInScraper().

在 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);
        }
    }
}

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

在此处查看示例:

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

这是我的 java class,对我有用。

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);
}}

这是您可以使用的方法 class

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

class test:

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