
相关免费学习推荐:python视频教程
创建maven工程,结构如下:

到官网https://www.jython.org/download.html下载Jython的jar包或者在maven的pom.xml文件中加入如下代码:
<dependency> <groupId>org.python</groupId> <artifactId>jython-standalone</artifactId> <version>2.7.0</version> </dependency>
创建JavaRunPython.java类:
package com.test;
import org.python.util.PythonInterpreter;
public class JavaRunPython {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a='hello world'; ");
interpreter.exec("print a;");
}
}输出结果如下:
立即学习“Java免费学习笔记(深入)”;
本支付接口的特点,主要是用xml文件来记录订单详情和支付详情。代码比较简单,只要将里面的商户号、商户key换成你自己的,将回调url换成你的网站,就可以使用了。通过这个实例也可以很好的了解一般在线支付接口的基本工作原理。其中的pay.config文件记录的是支付详情,order.config是订单详情
0

出现的console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.并不是错误,而是兼容所导致,解决方法如下:



在本地的D盘创建一个python脚本,文件名字为javaPythonFile.py,文件内容如下:
a = 1 b = 2 print (a + b)
创建JavaPythonFile.java类,内容如下:
package com.test;
import org.python.util.PythonInterpreter;
public class JavaPythonFile {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("D:\javaPythonFile.py");
}
}输出结果如下:
立即学习“Java免费学习笔记(深入)”;

在本地的D盘创建一个python脚本,文件名字为Runtime.py,文件内容如下:
print('RuntimeDemo')创建RuntimeFunction.java类,内容如下:
package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RuntimeFunction {
public static void main(String[] args) {
Process proc;
try {
proc = Runtime.getRuntime().exec("python D:\Runtime.py");
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
proc.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}运行结果如下:

在本地的D盘创建一个python脚本,文件名字为add.py,文件内容如下:
def add(a,b): return a + b
创建Function.java类,内容如下:
package com.test;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class Function {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("D:\add.py");
// 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
PyFunction pyFunction = interpreter.get("add", PyFunction.class);
int a = 5, b = 10;
//调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”
PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("the anwser is: " + pyobj);
}
}运行结果如下:

到此这篇关于详解java调用python的几种用法(看这篇就够了)的文章就介绍到这了。
相关免费学习推荐:php编程(视频)
以上就是详解java调用python的用法的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号