Java调用Python脚本

Java调用Python脚本

使用java.lang.Process类

Doc: 利用ProcessBuilder.start()Runtime.exec方法建立本机进程并返回一个可用于控制该进程并获取有关该进程信息的进程子类实例。经过方法getOutputStream,getInputStream'和getErrorStream`获取进程的输出流。java

举例

  • 无参数Python脚本:python

    # -*- coding: utf-8 -*-
    def Non_agr_func:
      print("java use python script")

    java程序调用:shell

    //调用过程可能出现IOException,须要处理异常
    String cmd = "python C:\\Users\\Non_arg_func.py";
    Process process = Runtime.getRuntime().exec(cmd);
    BufferedReader stream = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    String contentLine;
    String errorLine;
    while ((contentLine = stream.readLine()) != null) {
      System.out.print("content:"contentLine);   
      }
    while ((errorLine = errorStream.readLine()) != null) {
       System.out.print("error:"errorLine);  
       }
    stream.close();
  • 传参Python脚本服务器

    # -*- coding: utf-8 -*-
    import sys
    def args_func(a, b):
      return a+b
    
    if __name__ = '__main__':
      args = []
      for i in rang(1, len(sys.argv)):
          args.append(int(sys.argv[i]))
      print(args_func(args[0], args[1]))
    # sys.argv[0]表明python程序名,因此列表从1开始读取参数

    java程序调用:app

    //与无参Python脚本调用彻底一致,只须要在命令中传入须要的参数
    //下面两种命令的写法均可以
    String command = String.format("python %s %s %s", "C:\\Users\\arg_func.py", "1", "2");
    String[] args = new String[] {"python", "C:\\Users\\arg_func.py", "1", "2"};
    Process process = Runtime.getRuntime().exec(cmd);
    BufferedReader stream = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String contentLine;
    while ((contentLine = stream.readLine()) != null) {
      System.out.print("content:"contentLine);   
      }
  • 服务部署文档requirement.txtide

    程序终究是须要部署到服务器上的,而部署过程就须要引入咱们的Python中用到的模块,所以须要添加一个requirement.txt文档,用于一键引入须要的模块。这里咱们使用pipreqs工具来自动生成该文件工具

    1. 安装ui

      pip install pipreqs
    2. 用法编码

      #跟目录下使用命令
      pipreqs ./
    3. 报错code

      # Windows下报编码错误
      UnicodeDecodeError: 'gbk' codec can't decode byte 0xa8 in position 24: illegal multibyte sequence
      # 解决方法:指定编码
      pipreqs ./ --encoding=utf8
相关文章
相关标签/搜索