• python 基础 7.5 commands 模块


    一. commands 模块
     
    1.commands 模块只使用与linxu 的shell 模式下
    在我们平时码字时,经常需要调用系统脚本或者系统命令来解决很多问题,接下来,我们就介绍给大家一个很好用的模块commands,可以通过python 调用系统命令,调用系统命令commands 模块提供了三种解决方法,cmd 代表系统命令
     
    1》commands.getoutput(cmd)
    只返回执行 shell 命令结果:
     
    eg1:
    [root@www pythonscripts]# cat 1.py
    #!/usr/bin/python
    #conding = utf-8
     
    import commands
     
    cmd = 'ls /home/'
    print commands.getoutput(cmd)
    print type(commands.getoutput('cmd'))
     
    运行:
    [root@www pythonscripts]# python 1.py
    lost+found
    zabbix
    <type 'str'>
     
     
    2》commands.getstatusoutput(cmd)
    在上面我们执行shell命令的时候,我们的shell命令可能执行报错,或者异常退出,我们就要有一个条件来判断,shell最终执行的结果是什么。commands.getstatusoutput(cmd)的返回结果有两个值。
     
    [root@www pythonscripts]# cat 1.py
    #!/usr/bin/python
    # coding=utf-8
     
    import commands
    print '1.####commands 只对shell命令的结果输出####'
    cmd1 = 'ls /home/'
    print commands.getoutput(cmd1)
    print type(commands.getoutput('cmd1'))
    print ' '
     
    print '2.####commands.getstatusouptput 对shell命令的状态和输出结果进行输出####'
    cmd2 = 'ps -ef | grep httpd'
    c = status,output = commands.getstatusoutput(cmd2)
    print type(c)
    status,output = commands.getstatusoutput(cmd2)
    print status
    print type(status)
    print output
    print type(output)
     
    结果:
     
    解释:
    commands.getstatusoutput(cmd)的返回结果是一个tuple,第一个值是shell 执行的结果,如果shell 执行成功,返回0,否则为非0.第二个是一个字符串,就是我们shell 命令的执行结果,python通过一一 对应的方式复制给status 和 output,这个就是python 语言的巧妙之处。
     
    ###commands.getstatusoutput 的返回值是一个tuple类型
    ### 第一个值接收状态码,返回结果是一个init类型,如果返回值是0,说明执行正常,如果为非0,结果异常。
    ### 第二个接收返回结果,返回结果是一个str 类型
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
  • 相关阅读:
    出于安全考虑,office outlook禁止对潜在不安全因素的附件访问,如何解决
    70级圣骑士OK了,纪念下先!
    03.配置putty连接Linux系统,并实现中英文输入输出;配置vnc服务器
    想了解你好有的装备及属性吗,副本及飞行点的位置吗?简单!
    Windows Server 2008 下载、安装、激活
    同事的U盘写保护了!
    重新开始核心编程,Windows的开始
    如何知道某PC接入到交换机的哪个端口上
    DK装备获取线路总结
    Windows Server 2008 评估时间延期
  • 原文地址:https://www.cnblogs.com/lzcys8868/p/7819826.html
Copyright © 2020-2023  润新知