栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

java执行python代码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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:\anacondaLibsite-packages')  # 将此路径添加到系统环境变量中

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

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/339100.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号