java中如何调用python呢?
下文讲述java中调用python中方法的示例分享,如下所示:
java类中直接运行python语句
import org.python.util.PythonInterpreter;
public class FirstJavaScript {
public static void main(String args[]) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
interpreter.exec("print days[3];");
}
}
-----运行以上代码,将输出以下信息-----
Thu
java中调用本机python脚本中的函数
//1.建立一个python脚本,名字为: pythonTest.py
def adder(a, b):
return a + b
//建立java代码
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class TestPython {
public static void main(String args[]) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("D:\\Test\\pythonTest.py");
PyFunction func = (PyFunction) interpreter.get("adder",
PyFunction.class);
int a = 999, b =10;
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("结果:" + pyobj.toString());
}
}
---------------运行以上代码,将输出以下信息------
结果:1009
使用java直接运行python脚本
//建立脚本 testPython.py
#open files
print 'welcome java265.com'
number=[11,22,88]
print number
number.sort()
print number
number.append(0)
print number
print number.count(0)
print number.index(5)
//建立java文件
import org.python.util.PythonInterpreter;
public class TestPython {
public static void main(String args[]) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("D:\\test\testPython.py");
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


