zoukankan      html  css  js  c++  java
  • 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 类型
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
  • 相关阅读:
    4. Qt的容器类
    hdu 4507 数位dp(求和,求平方和)
    MVC3和MVC4中CRUD操作
    SSL 中证书能否够使用IP而不是域名
    TinyXml快速入门(一)
    C++ TinyXml操作(含源码下载)
    Tinyxml 操作XML
    msxml 操作xml
    MFC中全局变量的定义及使用
    VC++中操作XMLWin32实例
  • 原文地址:https://www.cnblogs.com/lzcys8868/p/7819826.html
Copyright © 2011-2022 走看看