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

python 调用linux shell的方法封装

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

python 调用linux shell的方法封装

在卖命敲代码时候,如果需要用到调用shell命令时候的方法封装

当然可以使用很多基础方法:
可以看下这个blog

不废话,上代码:

def python_shell_run(cmd,des="Python Call Run Shell",error_check=True,shell_env=None):
    """
    :Description:           Invoking shell commands using python
    :param cmd:             shell commands
    :param des:             shell commands description
    :param error_check:     shell run check
    :param shell_env:       shell environment variable {this is a dict data}
    :return:                shell output info
    """
    import commands
    shell_env_export = "{}&&".format("&&".join(map(lambda x: "export {}='{}'".format(x[0], x[1]), shell_env.items()))) if shell_env else ""
    run_status,run_output = commands.getstatusoutput(shell_env_export + cmd)
    if len(run_output) > 0:
        # success!
        print(run_output)
    if run_status != 0:
        # failed!
        print("Failed to run shell command:{}".format(des))
        if error_check:
            # u can specify to throw an exception
            raise Exception
    return run_output

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

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

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