java执行python代码

把调用流程封装为两个类:
第一个类是主执行类,里边提供一个静态方法用于调用Python代码

public class ExecuteCmd {
    /** 执行外部程序,并获取标准输出 */
    public static String execute(String[] cmd, String... encoding) {
        BufferedReader bReader = null;
        InputStreamReader sReader = null;
        try {
            Process p = Runtime.getRuntime().exec(cmd);


            /* 为"错误输出流"单独开一个线程读取之,否则会造成标准输出流的阻塞 */
            Thread t = new Thread(new InputStreamRunnable(p.getErrorStream(), "ErrorStream"));
            t.start();


            /* "标准输出流"就在当前方法中读取 */
            BufferedInputStream bis = new BufferedInputStream(p.getInputStream());


            if (encoding != null && encoding.length != 0) {
                sReader = new InputStreamReader(bis, encoding[0]);// 设置编码方式
            } else {
                sReader = new InputStreamReader(bis, "utf-8");
            }
            bReader = new BufferedReader(sReader);


            StringBuilder sb = new StringBuilder();
            String line;


            while ((line = bReader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }


            bReader.close();
            p.destroy();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

第二个类是处理的核心流程,如果执行出错的话,会打印出错误信息

class InputStreamRunnable implements Runnable {
    BufferedReader bReader = null;


    public InputStreamRunnable(InputStream is, String _type) {
        try {
            bReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(is), "UTF-8"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }




    public void run() {
        String line;
        int num = 0;
        try {
            while ((line = bReader.readLine()) != null) {
                System.out.println("---->"+String.format("%02d",num++)+" "+line);
            }
            bReader.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

在main方法中直接调用即可

public static void main(String[] args) {
	String[] arguments = new String[] { "python", "C:\\Users\\zk\\Desktop\\test\\mytest.py"};
	System.out.println(ExecuteCmd.execute(arguments));
}

另外由于是模拟cmd的方式执行,因此Python需要调用的库函数需要显式地添加到环境变量中,不然找不到对应的包,具体为:

import sys
sys.path.append('D:\\anaconda\Lib\site-packages')  # 将此路径添加到系统环境变量中

还有最后一个点,当前工作路径也要设置一下,不然会找不到当前工程目录下的文件,具体为:

import os
os.chdir('C:\\Users\\zk\\Desktop\\test')  # 设置当前工作路径

相关资源
https://blog.csdn.net/weixin_34198583/article/details/94097452

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值