java使用python
Python -> Native 代码 整体思路 先将Python 源代码转换成 C 代码,之后用 GCC 编译 C 代码为二进制模块 so/dll,接着进行一次 Java Native 接口封装,
⑵ 怎么使用java运行python脚本
1.直接执行Python脚本代码
引用 org.python包
1 PythonInterpreter interpreter = new PythonInterpreter();
2 interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); "); ///执行python脚本
2. 执行python .py文件
1 PythonInterpreter interpreter = new PythonInterpreter();
2 InputStream filepy = new FileInputStream("D:\\demo.py");
3 interpreter.execfile(filepy); ///执行python py文件
4 filepy.close();
3. 使用Runtime.getRuntime()执行脚本文件
这种方式和.net下面调用cmd执行命令的方式类似。如果执行的python脚本有引用第三方包的,建议使用此种方式。使用上面两种方式会报错java ImportError: No mole named arcpy。
1 Process proc = Runtime.getRuntime().exec("python D:\\demo.py");
2 proc.waitFor();
⑶ 如何在 Java 中调用 Python 代码
可以用Python的扩展来实现。Python本来是C实现的,封装二进制兼容的C++是很容易的。Java的话得通过JNI来实现,就是说在Python扩展里用C调用Java。另外,也可以写一个TCP服务来包装C++/Java的接口,通过网络来调用,这样更通用。
⑷ 如何在Java中调用Python代码
Jython(原JPython),是一个用Java语言写的Python解释器。
在没有第三方模块的情况下,通常选择利用Jython来调用Python代码,
它是一个开源的JAR包,你可以到官网下载
一个HelloPython程序
importorg.python.util.PythonInterpreter;
publicclassHelloPython{
publicstaticvoidmain(String[]args){
PythonInterpreterinterpreter=newPythonInterpreter();
interpreter.exec("print('hello')");
}
}
什么是PythonInterpreter?它的中文意思即是“Python解释器”。我们知道Python程序都是通过解释器来执行的,我们在Java中创建一个“解释器”对象,模拟Python解释器的行为,通过exec("Python语句")直接在JVM中执行Python代码,上面代码的输出结果为:hello
在Jvm中执行Python脚本
interpreter.execfile("D:/labs/mytest/hello.py");
如上,将exec改为execfile就可以了。需要注意的是,这个.py文件不能含有第三方模块,因为这个“Python脚本”最终还是在JVM环境下执行的,如果有第三方模块将会报错:javaImportError:Nomolenamedxxx
仅在Java中调用Python编写的函数
先完成一个hello.py代码:
defhello():
return'Hello'
在Java代码中调用这个函数:
importorg.python.core.PyFunction;
importorg.python.core.PyObject;
importorg.python.util.PythonInterpreter;
publicclassHelloPython{
publicstaticvoidmain(String[]args){
PythonInterpreterinterpreter=newPythonInterpreter();
interpreter.execfile("D:/labs/hello.py");
PyFunctionpyFunction=interpreter.get("hello",PyFunction.class);//第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
PyObjectpyObject=pyFunction.__call__();//调用函数
System.out.println(pyObject);
}
}
上面的代码执行结果为:Hello
即便只是调用一个函数,也必须先加载这个.py文件,之后再通过Jython包中所定义的类获取、调用这个函数。
如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”,例如:
__call__(newPyInteger(a),newPyInteger(b))
a,b的类型为Java中的int型,还有诸如:PyString(Stringstring)、PyList(Iterator
⑸ java怎么点用python脚本
首先得声明一下,java是java,python是python,你用java得环境跑python这不是找麻烦吗,但是并不是说不行,java有一个Jpython得库,你可以下载一下,这方面原理设计jni技术,建议了解一下,如果单纯想运行一个脚本可以找Jpython得api文档看看