linux java调用python_在Windows和Linux下使用jython实现Java与Python互操作

package com.test.utils;

import java.util.Properties;

import org.apache.commons.lang3.StringUtils;

import org.python.core.Py;

import org.python.core.PyFunction;

import org.python.core.PyObject;

import org.python.core.PySystemState;

import org.python.util.PythonInterpreter;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import com.test.ConfigBean;

import com.test.spring.SpringBeanFactory;

public class PyUtils

{

private static Logger logger = LoggerFactory.getLogger(PyUtils.class);

private static ConfigBean configBean = SpringBeanFactory.getBean("configBean");

private PythonInterpreter interpreter;

private PyFunction encryptFun;

private PyFunction decryptFun;

private static PyUtils self;

public String decrypt(String key, String data)

{

PyObject decryptFunctionResult = self.decryptFun.__call__(Py.newString(key), Py.newString(data));

return decryptFunctionResult.toString();

}

public String encrypt(String key, String data)

{

PyObject result = self.encryptFun.__call__(Py.newString(key), Py.newString(data));

return result.toString();

}

public static PyUtils getInstance()

{

if (self == null)

{

self = new PyUtils(configBean.getPythonDirectory());//此处是py脚本文件所在的目录

}

return self;

}

private PyUtils(String path)

{

if (StringUtils.endsWithIgnoreCase("develop", configBean.getEnv()))

{

}

else if (StringUtils.endsWithIgnoreCase("product", configBean.getEnv()))

{

Properties properties = new Properties();

properties.put("python.home", configBean.getJythonHome());//此处是jython安装后所在的目录,里面是有Lib目录等结构的

properties.put("python.console.encoding", "UTF-8");

properties.put("python.security.respectJavaAccessibility", "false");

properties.put("python.import.site", "false");

Properties systemProperties = System.getProperties();

PythonInterpreter.initialize(systemProperties, properties, new String[0]);

}

interpreter = new PythonInterpreter();

PySystemState pySystemState = Py.getSystemState();

pySystemState.path.add(path);

interpreter.exec("import sys");

interpreter.exec("print sys.path");

logger.info("Python path={}", pySystemState.path.toString());

interpreter.execfile("1.py");

interpreter.execfile("2.py");

interpreter.execfile("3.py");

interpreter.execfile("4.py");

interpreter.execfile("5.py");

interpreter.execfile("6.py");

encryptFun = interpreter.get("encrypt", PyFunction.class);

decryptFun = interpreter.get("decrypt", PyFunction.class);

}

public void close()

{

interpreter.cleanup();

interpreter.close();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值