社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用Jython从Java中使用Python函数运行Python函数

Shan Chathusanda Jayathilaka • 5 年前 • 274 次点击  

我想用Jython来执行一个Python函数,它位于Java中的一个Python项目中。 https://smartbear.com/blog/test-and-monitor/embedding-jython-in-java-applications/ 提供了用于此目的的示例代码。但在我的情况下,我得到了以下例外。

线程“main”回溯中的异常(最近一次调用最后一次):文件 “”中的第1行:没有名为 JythonTest模块

我的设想如下。

  1. 我在python项目(pythondev)中使用pycharm(jythontestmodule.py)创建了一个python模块,它包含以下函数。

    定义平方(值): 返回值*值

  2. 然后,我在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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/41051
 
274 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Shan Chathusanda Jayathilaka
Reply   •   1 楼
Shan Chathusanda Jayathilaka    6 年前

根据这个问题的上述评论部分的建议,我已经制定了我的问题的解决方案。下面的代码段将演示这一点。在这个解决方案中,我设置了 Python路径 作为模块文件的目录路径。

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路径 作为 所有模块的父目录路径 以便检测所有模块。