簡體   English   中英

Jython:無法在 Java 中導入 python function

[英]Jython: Can not import python function in Java

我正在嘗試開發一個簡單的 Java 應用程序,我希望它使用 Jython 使用一些 Python 代碼。 我正在嘗試從文件中運行 python 方法並收到此錯誤:

ImportError: cannot import name testFunction

只是嘗試一個簡單的例子,所以我可以看到問題出在哪里。 我的 python 文件test.py是這樣的:

def testFunction():
    print("testing")

還有我的 Java class:

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("path_to_file\\test.py");

interpreter.exec("from test import testFunction");

因此它可以正確找到該模塊,但其行為就像內部沒有名為testFunction的 function 一樣。

執行腳本文件如下。

interpreter.execfile("path/to/file/test.py");

如果您在腳本文件中聲明了函數,那么在執行上述語句后,您將可以從程序中執行這些函數,如下所示。

interpreter.exec("testFunction()");

因此,您不需要任何導入語句。

完整的示例代碼:

package jython_tests;

import org.python.util.PythonInterpreter;

public class RunJythonScript2 {
    public static void main(String[] args) {
        try (PythonInterpreter pyInterp = new PythonInterpreter()) {
            pyInterp.execfile("scripts/test.py");
            pyInterp.exec("testFunction()");
        }
    }
}

腳本:

def testFunction():
    print "testing"

Output:

testing

暫無
暫無

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

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