zoukankan      html  css  js  c++  java
  • Java调用Python脚本工具类

    [本文出自天外归云的博客园]

    在网上查了很多方法都不成功,在google上搜到一篇文章,做了一些小修改,能够处理中文输出。提取一个运行python脚本的Java工具类如下:

    package com.autox.util;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    
    public class RunPython {
        public static ArrayList<String> run_py(String script) {
            String s = null;
            ArrayList<String> result = new ArrayList<String>();
            ArrayList<String> error = new ArrayList<String>();
            try {
                Process p = Runtime.getRuntime().exec(script);
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream(), "GBK"));
                BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                while ((s = stdInput.readLine()) != null) {
                    result.add(s);
                }
                while ((s = stdError.readLine()) != null) {
                    error.add(s);
                }
                if (error != null) {
                    System.out.println(error);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
    }

    Java中调用方法如下:

    ArrayList<String> result = RunPython.run_py("python script_path args");
    for (String item : result) {
        System.out.println(item);
    }

    其中script_path需替换为Python脚本路径,args替换为向脚本传递的参数。

  • 相关阅读:
    Python time
    Python List/Tutle/Set/Str/Dict
    python os
    Python 学习之九九乘法表
    Pycharm配置
    python 打包exe:
    Linux 安装PHP扩展过程
    tkinter在循环中创建按钮以传递命令参数,闭包的坑
    tkinter
    设置greenplum用户和密码访问:
  • 原文地址:https://www.cnblogs.com/LanTianYou/p/6635386.html
Copyright © 2011-2022 走看看