Java实现调⽤jython执⾏python⽂件的⽅法
本⽂实例讲述了Java实现调⽤jython执⾏python⽂件的⽅法。分享给⼤家供⼤家参考,具体如下:
在web开发时候,经常在web环境使⽤本地环境的第三⽅库什么的,本⽂讲解java如何执⾏python⽂件。
⽹上说⽅法有三种,其实也就两种,下⾯着中介绍第⼆种通过(jython)。
⽅法⼀
java.lang.Runtime
Runtime rt = Runtime();
try {
Process proc = rt.exec("python /tmp/test.py");
}catch (Exception e){
e.printStackTrace();
}
⼩计⼀下:
1、Runtime()可以取得当前JVM的运⾏时环境,这也是在Java中唯⼀⼀个得到运⾏时环境的⽅法。
2、Runtime上其他⼤部分的⽅法都是实例⽅法,也就是说每次进⾏运⾏时调⽤时都要⽤到getRuntime⽅法。
3、Runtime中的exit⽅法是退出当前JVM的⽅法,估计也是唯⼀的⼀个吧,因为我看到System类中的exit实际上也是通过调⽤it()来退出JVM的,这⾥说明⼀下Java对Runtime返回值的⼀般规则(后边也提到了),0代表正常退出,⾮0代表异常中⽌,这只是Java的规则,在各个操作系统中总会发⽣⼀些⼩的混淆。
第⼆种(重点)
调⽤jython API
第⼀步:添加依赖
<!-- mvnrepository/artifact/org.python/jython -->
<dependency>
<groupId>org.python</groupId>
<artifactId>jython</artifactId>
<version>2.7.0</version>
</dependency>
第⼆步:新建⼀个Test.java测试类
import org.python.util.PythonInterpreter;
import java.util.Properties;
/**
* Author: 遇见⼩星
*Email:********************
* Date: 17-3-21
* Time: 下午8:18
* Describe: jpython test
*/
public class Test {
public static void main(String []args){
PythonInterpreter interpreter = new PythonInterpreter();
<("days=('Mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
<("print days[1];");
<("print 'created by tengxing on 2017.3'");
}
}
第三步:运⾏Test.java
Testing started at 下午9:40 ...
Tue
this is test.py
created by tengxing on 2017.3!
进程已结束,退出代码0
提醒可能报如下异常:
Exception in thread "main" ImportError: Cannot import site module and its dependencies: No module named site Determine if the following attributes are correct:
原因:没有初始化python.import.site
python转java代码解决:
public class Test {
public static void main(String []args){
Properties props = new Properties();
props.put("python.home", "path to the Lib folder");
props.put("ding", "UTF-8");
props.put("spectJavaAccessibility", "false");
props.put("python.import.site", "false");
Properties preprops = Properties();
PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter interpreter = new PythonInterpreter();
<("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
<("print days[1];");
<("print 'created by tengxing on 2017.3!'");
}
}
ok 完美
//调⽤python中的⽅法,并且打印结果
PyFunction func = (PyFunction) ("adder",PyFunction.class);
int a = 2010, b = 2;
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("anwser = " + String());
参考⽂章:
附:jython.jar点击此处。
更多java相关内容感兴趣的读者可查看本站专题:《》、《》、《》和《》
希望本⽂所述对⼤家java程序设计有所帮助。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。