您的位置:首页 > 编程语言 > Python开发

java调用python

2017-03-20 20:45 337 查看
本文记录下使用jython包来实现java代码中调用Python。

一、Maven加入

<dependency>
<groupId>org.python</groupId>
<artifactId>jython</artifactId>
<version>2.7.0</version>
</dependency>


二、代码

PythonDemo.java

package com.bob.testjava.python;

import org.python.util.PythonInterpreter;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Properties;

/**
* Created by zhangmingbo on 3/20/17.
*/
public class PythonDemo {

public static void main(String[] args) throws IOException {

//Create interpreter
Properties props = new Properties();
props.put("python.home", "path to the Lib folder");
props.put("python.console.encoding", "UTF-8"); // Used to prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
props.put("python.security.respectJavaAccessibility", "false"); //don't respect java accessibility, so that we can access protected members on subclasses
props.put("python.import.site", "false");

Properties preprops = System.getProperties();

PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter interp = new PythonInterpreter();

String pythonCodeStr = new String(Files.readAllBytes(new File("test.py").toPath()));
interp.exec(pythonCodeStr);

}

}


test.py

a = 2;
b = 4;
c = a * b;
print "I am from file", c


三、参考文档
http://bugs.jython.org/issue2355
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: