[英]Run a python function with arguments from java using jython
我想使用 jython 執行一個 Python 函數,該函數位於我的一個 Python 項目中。 https://smartbear.com/blog/test-and-monitor/embedding-jython-in-java-applications/為此目的提供了示例代碼。 但在我的場景中,我得到了以下異常。
線程“main”回溯中的異常(最近一次調用最后一次):文件“”,第 1 行,在 ImportError 中:沒有名為 JythonTestModule 的模塊
我的情況如下。
我使用包含以下函數的 PyCharm(JythonTestModule.py) 在我的 python 項目(pythonDev)中創建了一個 python 模塊。
def square(value): 返回值*值
然后我在我的 java 項目(javaDev)中創建了一個示例 java 類並調用了 python 模塊。
public static void main(String[] args) throws PyException{ PythonInterpreter pi = new PythonInterpreter(); pi.exec("from JythonTestModule import square"); pi.set("integer", new PyInteger(42)); pi.exec("result = square(integer)"); pi.exec("print(result)"); PyInteger result = (PyInteger)pi.get("result"); System.out.println("result: "+ result.asInt()); PyFunction pf = (PyFunction)pi.get("square"); System.out.println(pf.__call__(new PyInteger(5))); }
運行此 java 方法后,java 程序會生成上述異常。 我想知道這個提到的代碼段有什么問題。
根據這個問題上述評論部分的建議,我已經開發了我的問題的解決方案。 以下代碼段將演示這一點。 在這個解決方案中,我將python.path設置為我的模塊文件的目錄路徑。
public static void main(String[] args) throws PyException{
Properties properties = new Properties();
properties.setProperty("python.path", "/path/to/the/module/directory");
PythonInterpreter.initialize(System.getProperties(), properties, new String[]{""});
PythonInterpreter pi = new PythonInterpreter();
pi.exec("from JythonTestModule import square");
pi.set("integer", new PyInteger(42));
pi.exec("result = square(integer)");
pi.exec("print(result)");
PyInteger result = (PyInteger)pi.get("result");
System.out.println("result: "+ result.asInt());
PyFunction pf = (PyFunction)pi.get("square");
System.out.println(pf.__call__(new PyInteger(5)));
}
如果要使用 Jython 中的多個模塊,請將python.path添加為所有模塊的父目錄路徑,以便檢測所有模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.