Java调用Python程序方法、Jpython使用

Java调用Python程序方法、Jpython使用,第1张

由于最近需要在Java中跑Python代码,需要将Java和Python两种语言结合使用。学习了一下Jpython

一、简介

   Jython是一种完整的语言,而不是一个Java翻译器或仅仅是一个Python编译器,它是一个Python语言在Java中的完全实现。Jython也有很多从CPython中继承的模块库。Jython不像CPython或其他任何高级语言,它提供了对其实现语言的一切存取。所以Jython不仅给你提供了Python的库,同时也提供了所有的Java类。这使其有一个巨大的资源库。

二、Jpython使用

首先需要添加maven依赖

<dependency>
	<groupId>org.pythongroupId>
	<artifactId>jython-standaloneartifactId>
	<version>2.7.0version>
dependency>
1、在Java中执行python语句
public class JpythonTest {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("a=[10,8,3,1,7,0]; ");
        interpreter.exec("print(sorted(a));"); //此处python语句是3.x版本的语法
        interpreter.exec("print sorted(a);"); //此处是python语句是2.x版本的语法
    }
}

输出结果为:

2、在Java中执行Python脚本中的函数

首先在本地建立一个python脚本,命名为fun.py,做两个数的平方和。

def fun(a,b):
	return a*a + b*b

Java测试代码

public class JpythonTest {
    public static void main(String[] args) {

        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("D:\fun.py"); //fun 脚本位置

        // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
        PyFunction pyFunction = interpreter.get("fun", PyFunction.class);
        int a = 5, b = 10;

        //调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”
        PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b));
        System.out.println("平方和为: " + pyobj);
    }
}

结果:

3、使用Java执行python脚本,并传递参数

建立python脚本np.py,含有python第三方库的程序

import numpy as np
import sys

if __name__ == '__main__':
	a = [1,5,9,7,8,3]
	b = int(sys.argv[1])
	a.append(b)
	print("a: ",a)
	sum = np.sum(a)
	print("sum: ",sum)

Java测试代码

public class JpythonTest {
    public static void main(String[] args) {
        try {
            // 第一个参数为本地python路径, 第二个参数为脚本路径
            String[] args1 = new String[]{"D:\software\python3.8\python", "D:\np.py"};
            Process proc = Runtime.getRuntime().exec(args1); // 执行py文件
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            int index =0;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();

        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

结果:

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/734964.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存