Java调用Python脚本
来源:互联网 发布:美国指数型基金数据 编辑:程序博客网 时间:2024/05/18 11:35
1、本地环境安装的是Python 2.7.11
2、用maven下载jython依赖
<pre name="code" class="html"><dependency> <groupId>org.python</groupId> <artifactId>jython</artifactId> <version>2.7.0</version></dependency>3、python脚本编写
#coding:utf-8def adder(a, b): return a + b def mytest(str2): print str2 return 'call success !!!'
4、Java调用Python
<pre name="code" class="java">package test1;import java.util.Properties;import org.python.core.PyFunction;import org.python.core.PyInteger;import org.python.core.PyObject;import org.python.core.PyString;import org.python.util.PythonInterpreter;public class Java2Python {public static void main(String args[]) {Properties props = new Properties();props.put("python.home","D:/Python27/Lib");props.put("python.console.encoding", "UTF-8"); // Used to prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.props.put("python.security.respectJavaAccessibility", "false"); //don't respect java accessibility, so that we can access protected members on subclassesprops.put("python.import.site","false");Properties preprops = System.getProperties();PythonInterpreter.initialize(preprops, props, new String[0]);PythonInterpreter interpreter = new PythonInterpreter();interpreter.execfile("E:/workspace3/test1/src/main/java/test1/my_utils.py");PyFunction adder = (PyFunction) interpreter.get("adder", PyFunction.class);int a = 30, b = 50;PyObject pyobj = adder.__call__(new PyInteger(a), new PyInteger(b));System.out.println("anwser = " + pyobj.toString());PyFunction mytest = (PyFunction) interpreter.get("mytest", PyFunction.class);PyObject pyobj2 = mytest.__call__(new PyString("this is java project!!!"));System.out.println(pyobj2.toString());interpreter.close();}}
以上方式可以实现Java调用Python,但是在python 脚本中只能有python的原生api,如果在在脚本中有引入pandas,numpy之类的第三方扩展包,还是会是会找不到,这个问题正在查找是什么原因..
0 0
- Java调用Python脚本
- Java调用Python脚本
- java调用python脚本
- java调用Python脚本
- java调用python脚本
- java调用python脚本
- java调用python脚本方法
- java 调用python,shell脚本
- java调用python脚本之tomcat中
- java直接调用python脚本的例子
- java调用python脚本传参
- java调用python脚本文件大盘点
- java动态传参调用python脚本
- jpython的使用(Java调用python脚本)
- JAVA 调用python脚本的方法
- Python 调用shell脚本
- python调用Shell脚本
- python调用Shell脚本
- 手机浏览器打开手机上某个APP及注意事项
- Linux进程创建:fork,vfork,exec,clone总结
- SpringMVC+uploadify3.2.1版实现附件上传功能(未测试)
- poj 3061 尺取法
- AndroidStudio 断点调试
- Java调用Python脚本
- PAT-B 1033. 旧键盘打字
- <Python进阶读书笔记>之(二) 生成器
- mysql 连接出错 'mysqladmin flush-hosts'
- SharedPreferences存储多种类型
- scala映射和元组
- 【高精度算法】A-B(答案可负)
- QQ、Qzone分享的一些注意项
- 剑指offer——扑克牌顺子