简体   繁体   English

Jython:无法在 Java 中导入 python function

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

I am trying to develop a simple Java application and I want it to use some Python code using Jython.我正在尝试开发一个简单的 Java 应用程序,我希望它使用 Jython 使用一些 Python 代码。 I am trying to run a python method from a file and getting this error:我正在尝试从文件中运行 python 方法并收到此错误:

ImportError: cannot import name testFunction

Just trying a simple example so I can see where the problem is.只是尝试一个简单的例子,所以我可以看到问题出在哪里。 My python file test.py is like this:我的 python 文件test.py是这样的:

def testFunction():
    print("testing")

And my Java class:还有我的 Java class:

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

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

So it can correctly find the module but behaves like there is no function called testFunction inside.因此它可以正确找到该模块,但其行为就像内部没有名为testFunction的 function 一样。

Execute script files as follows.执行脚本文件如下。

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

If you have functions declared in the script file then after executing the above statement you'll have those functions available to be executed from the program as follows.如果您在脚本文件中声明了函数,那么在执行上述语句后,您将可以从程序中执行这些函数,如下所示。

interpreter.exec("testFunction()");

So, you don't need to have any import statement.因此,您不需要任何导入语句。

Complete Sample Code:完整的示例代码:

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

Script:脚本:

def testFunction():
    print "testing"

Output: Output:

testing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM