社区所有版块导航
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学习  »  Shan Chathusanda Jayathilaka  »  全部回复
回复总数  1
6 年前
回复了 Shan Chathusanda Jayathilaka 创建的主题 » 使用Jython从Java中使用Python函数运行Python函数

根据这个问题的上述评论部分的建议,我已经制定了我的问题的解决方案。下面的代码段将演示这一点。在这个解决方案中,我设置了 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路径 作为 所有模块的父目录路径 以便检测所有模块。