java调用Pytho脚本

1.加入依赖

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

2.Python脚本(脚本必须指定编码格式!!!否则java调用时报编码未设置的错)
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
import atexit
import logging
import os
import signal
import sys
from logging.handlers import RotatingFileHandler



logger = logging.getLogger()
MAX = 10 * 1024 * 1024
BACK_UP_COUNT = 10
def setup_logging():
    log_file = os.path.join(r'C:\\',"demo.log")
    logger.setLevel(logging.INFO)
    file_handler = RotatingFileHandler(log_file,"a",MAX,BACK_UP_COUNT)
    file_handler.setFormatter(
        logging.Formatter(
            "[%(asctime)%s] [%(process)d] [%(levelname)s] - %(module)s.%(funcName)s"
            "(%(filename)s:%(lineno)d) - %(message)s"
        )
    )
    logger.addHandler(file_handler)
PID_FILE = "fmpid.pid"
def write_pid():
    with open(PID_FILE,"w") as f:
        f.write('%s\n'%(os.getpid()))

def read_pid():
    try:
        with open(PID_FILE) as f:
            pid = int(f.read().strip())
    except Exception:
        pid = None
    return pid

def remove_pid():
    if os.path.exists(PID_FILE):
        os.remove(PID_FILE)

def sig_handler(sig,frame):
    logger.warning("shutting down, got signal %d"%sig)
    remove_pid()
    sys.exit(0)

def setup_application():
    pid = read_pid()
    if pid:
        sys.stdout.write('processing is running...\n')
        sys.exit(0)
    setup_logging()
    write_pid()
    atexit.register(remove_pid)
    for sig in (signal.SIGTERM,signal.SIGINT):
        signal.signal(sig,sig_handler)

def main():
    setup_application()
    # 逻辑
def add(a,b):
    return a + b

  3.java调用

import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

public class Test {
    public static void main(String[] args) {
/**
* 初始化java 调用python 时 PythonInterpreter 必要初始化参数
*/
     Properties props = new Properties();
// props.put("python.home", "path to the Lib folder");
// props.put("python.security.respectJavaAccessibility", "false");
props.put("python.console.encoding", "UTF-8");
props.put("python.import.site", "false");
Properties properties = System.getProperties();
PythonInterpreter.initialize(properties, props, new String[0]);

PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile("C:\\Users\\lenovo\\Desktop\\new.py"); // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型 PyFunction pyFunction = interpreter.get("add", PyFunction.class); int a = 5, b = 10; //调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型” PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b)); System.out.println("the 答案anwser is: " + pyobj); } }

  

posted @ 2021-06-25 08:30  沧海一粟为知己  阅读(78)  评论(0)    收藏  举报