java调用python

Java调用jython

准备:

1. sun-jre1.6, jython 2.5

2. 在官网下下个jython_installer-2.5.0.jar,一路next, 在 /jython-install-path/里有个jython.jar, 把这个jython.jar import 进Java Project 里边。

python代码: fibo.py

# Fibonacci numbers module

def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b

def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result


import org.python.core.PyException;
import org.python.core.PyFile;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;

public class TestJython {

/**
* 关注Jython这几个方面的内容:
* 1. 怎样从某个指定的路径import一个Jython模块?
* 2. 怎样调用模块里的方法?
* 3. java 与 jython 间的参数应该怎样进行传递?
*
* @param args
* @throws PyException
*/
public static void main(String []args)throws PyException
{
PythonInterpreter interp = new PythonInterpreter();

// 1.
// 引入系统模块,并将[./pythonsrc]加入模块搜索路径中去。
interp.exec("import sys");
interp.exec("sys.path.append('./pythonsrc')");

// 2. 引入 fibo, 执行fibo.fib(100), ok
interp.exec("import fibo");
interp.exec("fibo.fib(100)");

// 3. 在Java 程序中获得 python内置类型的变量值。
String text = "'this is a bad day'";
interp.exec("x = " + text + " + '!!!'");
interp.exec("print x");
PyObject object = interp.get("x");
PyString xString = object.__str__();
String outX = xString.asString();

interp.exec("_file = open('/home/fore/work/OaasSearch/search/oaas_search/workspace/oaas-search0.1/pythonsrc/fibo.py')");
object = interp.get("_file");
PyFile file = (PyFile)object;
PyString content = file.read(100);
System.out.println(content);

interp.exec("array = _file.read(100)");
String array = interp.get("array").asString();
System.out.println(array);

interp.exec("_file.close()");
file.close();
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值