java调用python

本文记录下使用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

转载于:https://www.cnblogs.com/bobsha/p/6591505.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值