zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    代码守恒定律
    第一个Dockerfile
    服务器项目白名单设置
    TOMCAT禁用不安全请求方式
    标准单例模式
    二进制,八进制,十进制,十六进制!!!!
    JAVA按层级遍历二叉树
    String的+
    安装 Rational Rose 启动报错:无法启动此程序,因为计算机中丢失 suite objects.dll
    java中文乱码问题
  • 原文地址:https://www.cnblogs.com/bobsha/p/6591505.html
Copyright © 2011-2022 走看看