• python之commands模块


    要获得shell命令的输出只需要`cmd`命令就可以了,

    需要得到命令执行的状态则需要判断$?的值, 在Python中有一个模块commands也很容易做到以上的效果.
    看一下三个函数:
    1). commands.getstatusoutput(cmd)
    用os.popen()执行命令cmd, 然后返回两个元素的元组(status, result),其中 status为int类型,result为string类型。cmd执行的方式是{ cmd ; } 2>&1, 这样返回结果里面就会包含标准输出和标准错误.


    2). commands.getoutput(cmd)
    只返回执行的结果, 忽略返回值.


    3). commands.getstatus(file) #现已被弃用
    返回ls -ld file执行的结果.


    看一下这些函数使用的例子:

    >>> import commands

    >>> commands.getstatusoutput('ls /bin/ls')

    (0, '/bin/ls')

    >>> commands.getstatusoutput('cat /bin/junk')

    (256, 'cat: /bin/junk: No such file or directory')

    >>> commands.getstatusoutput('/bin/junk')

    (256, 'sh: /bin/junk: not found')

    >>> commands.getoutput('ls /bin/ls')

    '/bin/ls'

    >>> commands.getstatus('/bin/ls')    #该函数已被python丢弃,不建议使用,它返回 ls -ld file 的结果(String)(返回结果太奇怪了,难怪被丢弃)

    '-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

     1 #!/usr/bin/python
     2 #coding:utf-8
     3 import os,sys,commands
     4 
     5 def openfile():
     6     grains = {}
     7     _open_file=65533
     8     try:
     9         getulimit=commands.getstatusoutput('source /etc/profile;ulimit -n')
    10     except Exception,e:
    11         pass
    12     if getulimit[0]==0:
    13        _open_file=int(getulimit[1])
    14     grains['max_open_file'] = _open_file
    15     return grains
  • 相关阅读:
    collections.ChainMap类合并字典或映射
    collections.namedtuple()命名序列元素
    过滤、修改和替换列表数据
    快速排序
    itertools.groupby()分组字典列表
    operator.attrgetter() 进行对象排序
    operator.itemgetter() 字典列表排序
    collections.Counter类统计列表元素出现次数
    递归
    正则表达式的一些题
  • 原文地址:https://www.cnblogs.com/wjoyxt/p/5087951.html
Copyright © 2020-2023  润新知