在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来截取结果

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>