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

  • 相关阅读:
    iframe与动作连处理
    selenium其他自动化操作
    使用seleniun模拟登陆qq空间
    selenium基本使用
    验证码识别 云打码之古诗文网验证识别
    图片爬取基础
    centos8下LAMP搭建Nextcloud
    浅谈centos8与centos7
    DHCP服务器配置及测试
    使用Apache服务器实现Nginx反向代理
  • 原文地址:https://www.cnblogs.com/bobsha/p/6591505.html
Copyright © 2011-2022 走看看