java如何调用python脚本

353次阅读
没有评论

java如何调用python脚本

常见的java调用python脚本方式有两种,下面给大家介绍一下:

·通过Jython.jar提供的类库实现

·通过Runtime.getRuntime()开启进程来执行脚本文件

这两种方法我都尝试过,个人推荐第二种方法,因为Python有时需要用到第三方库,比如requests,而Jython不支持。所以本地安装Python环境并且安装第三库再用Java调用是最好的方法。

下面通过两个小例子,分别是不带参数和带参数的,展示如何使用Java调用Python脚本:

Python代码:

def hello():
    print('Hello,Python')
 
if __name__ == '__main__':
  hello()

Java代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
 
public class HelloPython {
  public static void main(String[] args) {
    String[] arguments = new String[] {"python", "E://workspace/hello.py"};
        try {
            Process process = Runtime.getRuntime().exec(arguments);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),
            "GBK"));
            String line = null;
          while ((line = in.readLine()) != null) {  
              System.out.println(line);  
          }  
          in.close();
          //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功,
            //返回值为1表示调用python脚本失败,这和我们通常意义上见到的0与1定义正好相反
          int re = process.waitFor();  
          System.out.println(re);
        } catch (Exception e) {
            e.printStackTrace();
        }  
  }
}

其中说明一点,BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),”GBK”));这段代码中的GBK是为了防止Python输出中文时乱码加的。

运行结果:

java如何调用python脚本

接下来是带参数的,Python代码:

import sys
 
def hello(name,age):
  print('name:'+name)
  print('age:'+age)
 
if __name__ == '__main__':
  hello(sys.argv[1], sys.argv[2])

Java代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
 
public class HelloPython {
  public static void main(String[] args) {
    String[] arguments = new String[] {"python", "E://workspace/hello.py","lei","23"};
        try {
            Process process = Runtime.getRuntime().exec(arguments);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),
            "GBK"));
            String line = null;
          while ((line = in.readLine()) != null) {  
              System.out.println(line);  
          }  
          in.close();
          //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功,
            //返回值为1表示调用python脚本失败,这和我们通常意义上见到的0与1定义正好相反
          int re = process.waitFor();  
          System.out.println(re);
        } catch (Exception e) {
            e.printStackTrace();
        }  
  }
}

运行结果:

java如何调用python脚本

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-25发表,共计2275字。
新手QQ群:570568346,欢迎进群讨论 Python51学习