找回密码
 立即注册
首页 业界区 业界 [Java/Python] Java 基于命令行调用 Python

[Java/Python] Java 基于命令行调用 Python

士沌 2025-6-9 14:00:58
需求描述


  • 利用 Java 基于命令行调用 Python
实现步骤

安装 Python + PIP 环境

以基于 Ubuntu 24 的 Docker 环境为例


  • Dockerfile
  1. # OS: Ubuntu 24.04
  2. FROM swr.cn-north-4.myhuaweicloud.com/xxx/eclipse-temurin:17-noble
  3. COPY ./target/*.jar /app.jar
  4. COPY ./target/classes/xxx/ /xxx/
  5. # install : python + pip (前置操作: 更新 apt 源)
  6. RUN sed -i 's#http[s]*://[^/]*#http://mirrors.aliyun.com#g' /etc/apt/sources.list \
  7.   && apt-get update \
  8.   && apt-get -y install vim \
  9.   && apt-get -y install --no-install-recommends python3 python3-pip python3-venv \
  10.   && python3 -m venv $HOME/.venv \
  11.   && . $HOME/.venv/bin/activate \ # 注:Linux 中 高版本 Python (3.5以上),必须在虚拟环境下方可正常安装所需依赖包
  12.   && pip install -i https://mirrors.aliyun.com/pypi/simple/ can cantools
  13. #   && echo "alias python=python3" >> ~/.bashrc \ # Java程序的子进程调用中试验:未此行命令未生效;但开发者独自登录 docker 容器内,有生效
  14. #   && echo '. $HOME/.venv/bin/activate' >> ~/.bashrc \ # Java程序的子进程调用中试验:未此行命令未生效;但开发者独自登录 docker 容器内,有生效
  15. #   && echo 'export PYTHON=$HOME/.venv/bin/python' >> /etc/profile \ # Java程序的子进程调用中试验:未此行命令未生效;但开发者独自登录 docker 容器内,有生效
  16. #  && echo '. /etc/profile' > $HOME/app.sh \ # Java程序的子进程调用中试验:未测通,有衍生问题未解决掉
  17. #  && echo 'java ${JAVA_OPTS:-} -jar app.jar > /dev/null 2>&1 &' >> $HOME/app.sh \  # Java程序的子进程调用中试验:未测通,有衍生问题未解决掉
  18. #  && echo 'java ${JAVA_OPTS:-} -jar app.jar' >> $HOME/app.sh \  # Java程序的子进程调用中试验:未测通,有衍生问题未解决掉
  19. #  && chmod +x $HOME/app.sh \  # Java程序的子进程调用中试验:未测通,有衍生问题未解决掉
  20. #  && chown 777 $HOME/app.sh  # Java程序的子进程调用中试验:未测通,有衍生问题未解决掉
  21. EXPOSE 8080
  22. # ENTRYPOINT exec sh $HOME/app.sh # Java程序的子进程调用中试验:未测通,有衍生问题未解决掉
  23. ENTRYPOINT exec java ${JAVA_OPTS:-} -DPYTHON=$HOME/.venv/bin/python -jar app.jar # 通过 Java 获取 JVM 参数( System.getProperty("PYTHON") ) 方式获取 【 Python 可执行文件的绝对路径】的值
复制代码
编写和准备 Python 业务脚本


  • step1 编写 Python 业务脚本 (略)
  • step2 如果 Python 脚本在 JAVA 工程内部(JAR包内),则需在 执行 Python 脚本前,将其提前拷贝为一份新的脚本文件到指定位置。
  1. public XXX {
  2.     private static String scriptFilePath;
  3.     public static String TMP_DIR = "/tmp/xxx-sdk/";
  4.        
  5.         static {
  6.         prepareHandleScript( TMP_DIR );
  7.         }
  8.     /**
  9.      *  准备脚本文件到目标路径
  10.      * @note 无法直接执行 jar 包内的脚本文件,需要拷贝出来。
  11.      * @param targetScriptDirectory 目标脚本的文件夹路径
  12.      *     而非脚本文件路径 eg: "/tmp/xxx-sdk"
  13.      */
  14.     @SneakyThrows
  15.     public static void prepareHandleScript(String targetScriptDirectory){
  16.         File file = new File(targetScriptDirectory);
  17.         //如果目标目录不存在,则创建该目录
  18.         if (!file.exists() && !file.isDirectory()) {
  19.             file.mkdirs();
  20.         }
  21.         File targetScriptFile = new File(targetScriptDirectory + "/xxx-converter.py");// targetScriptFile = "\tmp\xxx-sdk\xxx-converter.py"
  22.         scriptFilePath = targetScriptFile.getAbsolutePath(); // scriptFilePath = "D:\tmp\xxx-sdk\xxx-converter.py"
  23.         URL resource = CanAscLogGenerator.class
  24.             .getClassLoader()
  25.             .getResource( "bin/xxx-converter.py");
  26.         InputStream converterPythonScriptInputStream = null;
  27.         try {
  28.             converterPythonScriptInputStream = resource.openStream();
  29.             FileUtils.copyInputStreamToFile( converterPythonScriptInputStream, targetScriptFile );
  30.         } catch (IOException exception){
  31.             log.error("Fail to prepare the script!targetScriptDirectory:{}, exception:", targetScriptDirectory, exception);
  32.             throw new RuntimeException(exception);
  33.         } finally {
  34.             if(converterPythonScriptInputStream != null){
  35.                 converterPythonScriptInputStream.close();
  36.             }
  37.         }
  38.     }
  39. }
复制代码
Java 调用 Python 脚本

关键点:程序阻塞问题

1.png


  • 推荐文献


  • 执行Runtime.exec()需要注意的陷阱 - 博客园 【推荐】
程序阻塞问题


  • 通过 Process实例.getInputStream() 和 Process实例.getErrorStream() 获取的输入流错误信息流缓冲池向当前Java程序提供的,而不是直接获取外部程序的标准输出流和标准错误流。
  • 缓冲池的容量是一定的。
因此,若外部程序在运行过程中不断向缓冲池输出内容,当缓冲池填满,那么: 外部程序暂停运行直到缓冲池有空位可接收外部程序的输出内容为止。(
注:采用xcopy命令复制大量文件时将会出现该问题


  • 解决办法: 当前的Java程序不断读取缓冲池的内容,从而为腾出缓冲池的空间。
  1. Runtime r = Runtime.getRuntime();
  2. try {
  3.     Process proc = r.exec("cmd /c dir"); // 假设该操作为造成大量内容输出
  4.           // 采用字符流读取缓冲池内容,腾出空间
  5.           BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gbk")));
  6.           String line = null;
  7.           while ((line = reader.readLine()) != null){
  8.              System.out.println(line);
  9.           }
  10.        
  11.           /* 或采用字节流读取缓冲池内容,腾出空间
  12.            ByteArrayOutputStream pool = new ByteArrayOutputStream();
  13.            byte[] buffer = new byte[1024];
  14.            int count = -1;
  15.            while ((count = proc.getInputStream().read(buffer)) != -1){
  16.              pool.write(buffer, 0, count);
  17.              buffer = new byte[1024];
  18.            }
  19.            System.out.println(pool.toString("gbk"));
  20.            */
  21.        
  22.           int exitVal = proc.waitFor();
  23.           System.out.println(exitVal == 0 ? "成功" : "失败");
  24. } catch(Exception e){
  25.           e.printStackTrace();
  26. }
复制代码

  • 注意:外部程序在执行结束后需自动关闭;否则,不管是字符流还是字节流均由于既读不到数据,又读不到流结束符,从而出现阻塞Java进程运行的情况。
cmd的参数 “/c” 表示当命令执行完成后关闭自身
关键点: Java Runtime.exec() 方法

基本方法: Runtime.exec()


  • 首先,在Linux系统下,使用Java调用Python脚本,传入参数,需要使用Runtime.exec()方法
即 在java中使用shell命令
这个方法有两种使用形式:

  • 方式1 无参数传入 ,直接执行Linux相关命令: Process process = Runtime.getRuntime().exec(String cmd);
无参数可以直接传入字符串,如果需要传参数,就要用方式2的字符串数组实现。


  • 方式2 有参数传入,并执行Linux命令: Process process = Runtime.getRuntime().exec(String[] cmd);
执行结果


  • 使用exec方法执行命令,如果需要执行的结果,用如下方式得到:
  1.         String line;
  2.     while ((line = processInputStream.readLine()) != null) { // InputStream processInputStream = process.getInputStream();
  3.             System.out.println(line);
  4.          if ("".equals(line)) {
  5.                break;
  6.           }
  7.     }
  8.     System.out.println("line ----> " + line);
复制代码
查看错误信息
  1.         BufferedReader errorResultReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
  2.         String errorLine;
  3.         while ((errorLine = shellErrorResultReader.readLine()) != null) {
  4.             System.out.println("errorStream:" + errorLine);
  5.     }
  6.     int exitCode = process.waitFor();
  7.     System.out.println("exitCode:" + exitCode);
复制代码
简单示例
  1.         String result = "";
  2.         String[] cmd = new String [] { "pwd" };
  3.         Process process = Runtime.getRuntime().exec(cmd);
  4.         InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
  5.         LineNumberReader input = new LineNumberReader(inputStreamReader);
  6.         result = input.readLine();
  7.         System.out.println("result:" + result);
复制代码
关键点: python 绝对路径


  • 查看python使用的路径,然后在Java调用的时候写出绝对路径。
以解决 Linux 环境中的 Python 3.X 的虚拟环境异常问题(pip install XXX : error: externally-managed-environment)。
Python 虚拟环境管理 - 博客园/千千寰宇
Cannot run program “python“: error=2, No such file or director (因虚拟环境问题,找不到python命令和pip安装的包)
Java 调用 Python 的实现 (必读)
  1. @Slf4j
  2. public class XxxxGenerator implements IGenerator<XxxxSequenceDto> {
  3.     //python jvm 变量 (`-DPYTHON=$HOME/.venv/bin/python`)
  4.     public static String PYTHON_VM_PARAM = "PYTHON";//System.getProperty(PYTHON_VM_PARAM)
  5.     //python 环境变量名称 //eg: "export PYTHON=$HOME/.venv/bin/python" , pythonEnv="$HOME/.venv/bin/python"
  6.     public static String PYTHON_ENV_PARAM = "PYTHON";//;System.getenv(PYTHON_ENV_PARAM);
  7.     private static String PYTHON_COMMAND ;
  8.     //默认的 python 命令
  9.     private static String PYTHON_COMMAND_DEFAULT = "python";
  10.        
  11.         //...
  12.     static {
  13.         PYTHON_COMMAND = loadPythonCommand();
  14.         log.info("PYTHON_COMMAND:{}, PYTHON_VM:{}, PYTHON_ENV:{}", PYTHON_COMMAND, System.getProperty(PYTHON_VM_PARAM), System.getenv(PYTHON_ENV_PARAM) );
  15.                
  16.                 //...
  17.     }
  18.     /**
  19.      * 加载 python 命令的可执行程序的路径
  20.      * @note
  21.      *   Linux 中,尤其是 高版本 Python(3.x) ,为避免 Java 通过 `Runtime.getRuntime().exec(args)` 方式 调用 Python 命令时,报找不到 可执行程序(`Python` 命令)\
  22.      *   ————建议: java 程序中使用的 `python` 命令的可执行程序路径,使用【绝对路径】
  23.      * @return
  24.      */
  25.     private static String loadPythonCommand(){
  26.         String pythonVm = System.getProperty(PYTHON_VM_PARAM);
  27.         String pythonEnv = System.getenv(PYTHON_ENV_PARAM);
  28.         String pythonCommand = pythonVm != null?pythonVm : pythonEnv;
  29.         pythonCommand = pythonCommand != null?pythonCommand : PYTHON_COMMAND_DEFAULT;
  30.         return pythonCommand;
  31.     }
  32.     /**
  33.      * 业务方法: CAN ASC LOG 转 BLF
  34.      * @param ascLogFilePath
  35.      * @param blfFilePath
  36.      */
  37.     protected void convertToBlf(File ascLogFilePath, File blfFilePath){
  38.         //CanAsclogBlfConverterScriptPath = "/D:/Workspace/CodeRepositories/xxx-platform/xxx-sdk/xxx-sdk-java/target/classes/bin/can-asclog-blf-converter.py"
  39.         //String CanAsclogBlfConverterScriptPath = CanAscLogGenerator.class.getClassLoader().getResource("bin/can-asclog-blf-converter.py").getPath();
  40.         String canAscLogBlfConverterScriptPath = XxxxGenerator.scriptFilePath;//python 业务脚本的文件路径, eg: "D:\tmp\xxx-sdk\can-asclog-blf-converter.py"
  41.         //String [] args = new String [] {"python", "..\\bin\\can-asclog-blf-converter.py", "-i", ascLogFilePath, "-o", blfFilePath};// ascLogFilePath="/tmp/xxx-sdk/can-1.asc" , blfFilePath="/tmp/xxx-sdk/can-1.blf"
  42.         String [] args = new String [] { PYTHON_COMMAND, canAscLogBlfConverterScriptPath, "-i", ascLogFilePath.getPath(), "-o", blfFilePath.getPath()};
  43.         log.info("args: {} {} {} {} {} {}", args);
  44.         Process process = null;
  45.         Long startTime = System.currentTimeMillis();
  46.         try {
  47.             process = Runtime.getRuntime().exec(args);
  48.             Long endTime = System.currentTimeMillis();
  49.             log.info("Success to convert can asc log file to blf file!ascLogFile:{}, blfFile:{}, timeConsuming:{}ms, pid:{}", ascLogFilePath, blfFilePath, endTime - startTime, process.pid());
  50.         } catch (IOException exception) {
  51.             log.error("Fail to convert can asc log file to blf file!ascLogFile:{}, blfFile:{}, exception:", ascLogFilePath, blfFilePath,  exception);
  52.             throw new RuntimeException(exception);
  53.         }
  54.         //读取 python 脚本的标准输出
  55.         // ---- input stream ----
  56.         List<String> processOutputs = new ArrayList<>();
  57.         try(
  58.             InputStream processInputStream = process.getInputStream();
  59.             BufferedReader processReader = new BufferedReader( new InputStreamReader( processInputStream ));
  60.         ) {
  61.             Long readProcessStartTime = System.currentTimeMillis();
  62.             String processLine = null;
  63.             while( (processLine = processReader.readLine()) != null ) {
  64.                 processOutputs.add( processLine );
  65.             }
  66.             process.waitFor();
  67.             Long readProcessEndTime = System.currentTimeMillis();
  68.             log.info("Success to read the can asc log to blf file's process standard output!timeConsuming:{}ms", readProcessEndTime - readProcessStartTime );
  69.             log.info("processOutputs(System.out):{}", JSON.toJSONString( processOutputs ));
  70.         } catch (IOException exception) {
  71.             log.error("Fail to get input stream!IOException:", exception);
  72.             throw new RuntimeException(exception);
  73.         } catch (InterruptedException exception) {
  74.             log.error("Fail to wait for the process!InterruptedException:{}", exception);
  75.             throw new RuntimeException(exception);
  76.         }
  77.         // ---- error stream ----
  78.         List<String> processErrors = new ArrayList<>();
  79.         try(
  80.             InputStream processInputStream = process.getErrorStream();
  81.             BufferedReader processReader = new BufferedReader( new InputStreamReader( processInputStream ));
  82.         ) {
  83.             Long readProcessStartTime = System.currentTimeMillis();
  84.             String processLine = null;
  85.             while( (processLine = processReader.readLine()) != null ) {
  86.                 processErrors.add( processLine );
  87.             }
  88.             process.waitFor();
  89.             Long readProcessEndTime = System.currentTimeMillis();
  90.             log.error("Success to read the can asc log to blf file's process standard output!timeConsuming:{}ms", readProcessEndTime - readProcessStartTime );
  91.             log.error("processOutputs(System.err):{}", JSON.toJSONString( processOutputs ));
  92.         } catch (IOException exception) {
  93.             log.error("Fail to get input stream!IOException:", exception);
  94.             throw new RuntimeException(exception);
  95.         } catch (InterruptedException exception) {
  96.             log.error("Fail to wait for the process!InterruptedException:{}", exception);
  97.             throw new RuntimeException(exception);
  98.         }
  99.         if( processErrors.size() > 0 ) {
  100.             throw new RuntimeException( "convert to blf failed!\nerrors:" + JSON.toJSONString(processErrors) );
  101.         }
  102.     }
  103. }
复制代码
Y 推荐文献


  • [Python] 包管理器Pip - 博客园/千千寰宇
  • [Python] Python 基础教程 - 博客园/千千寰宇
  • Python 虚拟环境管理 - 博客园/千千寰宇
  • 执行Runtime.exec()需要注意的陷阱 - 博客园 【推荐】
程序阻塞问题
X 参考文献


  • 解决Linux环境使用Java调用Python脚本的问题 - CSDN 【推荐】
在Java调用的时候写出绝对路径: String[] cmd = {"/root/miniconda3/bin/python", "/home/test.py"};


  • java调用外部程序(Runtime.getRuntime().exec)详解 - CSDN 【推荐】
  • yarn上报错Cannot run program “python“: error=2, No such file or directory
Cannot run program “python“: error=2, No such file or director  (因虚拟环境问题,找不到python命令和pip安装的包)
    本文作者:        千千寰宇   
    本文链接:         https://www.cnblogs.com/johnnyzen   
    关于博文:评论和私信会在第一时间回复,或直接私信我。   
    版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA     许可协议。转载请注明出处!
    日常交流:大数据与软件开发-QQ交流群: 774386015        【入群二维码】参见左下角。您的支持、鼓励是博主技术写作的重要动力!   

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册