在java中调用python脚本的三种方法
作者:努力提升的码农
实际工程项目中可能会用到Java和python两种语言结合进行,这样就会涉及到一个问题,就是怎么用Java程序来调用已经写好的python脚本呢,这篇文章主要给大家介绍了关于在java中调用python脚本的三种方法,需要的朋友可以参考下
前言
推荐使用第三种方法,因为只有第三种方法使用Runtime.getRuntime()才能执行含有第三方库(numpy,matlab,pandas等库)的python脚本。
方法一:在java程序中执行Python语句
1.首先在maven中添加依赖
<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-standalone</artifactId>
    <version>2.7.0</version>
</dependency>2.使用Jpython中的PythonInterpreter执行Python语句
public class Tool{
    public static void main(String [] args){
        PythonInterpreter interpreter = new PythonInterpreter();
		interpreter.exec("print("This is a JPython text")");
        interpreter.exec("print(2+3)");
    }
}方法二:java执行python脚本(不支持第三方库)
1.首先在maven中添加依赖(也是依赖Jpython包)
<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-standalone</artifactId>
    <version>2.7.0</version>
</dependency>2.创建一个Python脚本
#当我们的Python脚本中有汉字的时候,需要在脚本的第一行写coding = utf-8 来告诉编译器编码方式是什么 # -*- coding: UTF-8 -*- a = 'This is a test' print(a)
3.在java中执行python脚本
public class Tool{
    public static void main(String [] args){
        PythonInterpreter interpreter = new PythonInterpreter();
		interpreter.execfile("./text.py");//放脚本的位置
		interpreter.cleanup();
		interpreter.close();
    }
}方法三:使用Runtime.getRuntime()执行Python脚本
1.不需要传递参数的例子
先创建一个简单的调用第三方库的Python脚本
import numpy as np a = np.arange(10) print(a)
然后使用 Runtime.getRuntime() 方法执行python脚本
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Tool {
    public static void main(String[] args) {
        try {
            Process proc = Runtime.getRuntime().exec("test.py");//执行脚本
            //用输入输出流来截取结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while((line = reader.readLine()) != null){
                System.out.println(line);
            }
            reader.close();
            proc.waitFor();
        } catch (IOException e) {
             throw new RuntimeException(e);
        } catch (InterruptedException e) {
             throw new RuntimeException(e);
        } 
    }
}2.需要传递参数的例子
import sys
def sum(a, b, c):
	return a+b+c
if __name__ == "__main__":	
	a=(int(sys.argv[1]))
	b=(int(sys.argv[2]))
	c=(int(sys.argv[3]))
	s=sum(a,b,c)
	print("finish!!!")
	print(s)sys.argv用于获取参数url1,url2,乃至更多,sys.argv[0]代表python程序名
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Tool {
    public static void main(String [] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
		int b = scanner.nextInt();
		int c = scanner.nextInt();
        try {
            String[] my_args =new String[] {"python","test.py",String.valueOf(a),String.valueOf(b),String.valueOf(c)};
            Process proc =  Runtime.getRuntime().exec(my_args);//执行脚本
            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while((line = reader.readLine()) != null){
                System.out.println(line);
            }
            reader.close();
            proc.waitFor();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}my_args数组里面存放的参数{“python”,“test.py”,String.valueOf(a),String.valueOf(b),String.valueOf©},第一个是固定的就写’python‘,第二个是我们要执行的python脚本的位置(注意路径),后面的是我们要传递的参数也就是url1,url2等等(和Python脚本所接收的内容互相对应)
这种方式我们需要使用输入流输出流BufferedReader来截取结果
总结
到此这篇关于在java中调用python脚本的三种方法的文章就介绍到这了,更多相关java调用python脚本内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
