簡體   English   中英

從Java調用python模塊

[英]Calling python module from Java

我想使用“ PythonInterpreter”從Java的python模塊調用函數,這是我的Java代碼

PythonInterpreter interpreter = new PythonInterpreter();

interpreter.exec("import sys\nsys.path.append('C:\\Python27\\Lib\\site-packages')\nimport helloworld");

PyObject someFunc = interpreter.get("helloworld.getName");

PyObject result = someFunc.__call__();

String realResult = (String) result.__tojava__(String.class);

System.out.println(realResult);

Python代碼(helloworld.py)如下:

    from faker import Factory
    fake = Factory.create()

    def getName():
       name = fake.name()
       return name  

我面臨的問題是當我調用解釋器.get時返回空PyObject。

知道發生了什么事嗎? python代碼在IDLE上運行良好

編輯

我只是在代碼中做了一些更改,如下所示

PythonInterpreter interpreter = new PythonInterpreter();

interpreter.exec("import sys\nsys.path.append('C:\\Python27\\Lib\\site-packages')\nimport helloworld");


PyInstance wrapper = (PyInstance)interpreter.eval("helloworld" + "(" + ")");  

PyObject result = wrapper.invoke("getName()");

String realResult = (String) result.__tojava__(String.class);

System.out.println(realResult);

我在python模塊中引入了一個類

from faker import Factory

class helloworld:

def init(self):
    fake = Factory.create()

def getName():
    name = fake.name()
    return name 

現在出現以下錯誤

Exception in thread "main" Traceback (innermost last):
  File "<string>", line 1, in ?
TypeError: call of non-function (java package 'helloworld')
  1. 您不能在PythonInterpreter.get使用python屬性訪問。 只需使用屬性名稱即可獲取模塊,然后從中獲取屬性。
  2. (編輯部分)Python代碼已完全損壞。 請參見下面的正確示例。 並且,當然是www.python.org
  3. (編輯部分) PyInstance.invoke第一個參數應該是方法名稱。
  4. 您可以在下面找到這兩種情況的工作代碼示例

Main.java

import org.python.core.*;
import org.python.util.PythonInterpreter;

public class Main {

    public static void main(String[] args) {
        test1();
        test2();
    }

    private static void test1() {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("import hello_world1");
        PyObject func = interpreter.get("hello_world1").__getattr__("get_name");
        System.out.println(func.__call__().__tojava__(String.class));
    }

    private static void test2() {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("from hello_world2 import HelloWorld");
        PyInstance obj = (PyInstance)interpreter.eval("HelloWorld()");
        System.out.println(obj.invoke("get_name").__tojava__(String.class));
    }
}

hello_world1.py

def get_name():
    return "world"

hello_world2.py

class HelloWorld:
    def __init__(self):
        self.world = "world"

    def get_name(self):
        return self.world

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM