python处理shell的几个模块

This is the content of my super blog post.

python处理shell的几个模块

运维写python难免要与shell命令交互,介绍几个常用模块


  1. os.system模块

    >>> import os
    >>> a = os.system('ls')
    test.txt
    >>> print a
    0
    >>> a = os.system('lsl')
    sh: lsl: command not found
    >>> print a
    32512
    

    执行shell命令,并且直接输出结果,结果不可捕获,成功返回0

  2. os.popen模块

    >>> import os
    >>> a = os.popen('ls')
    >>> print type(a)
    <type 'file'>
    >>> print a.read()
    test.txt
    
    >>>
    

    执行shell命令,可以捕获到结果,用file的方式返回,对其进行读取使用read()

  3. sh模块

    执行shell命令

    >>> import sh
    >>> sh.ls('.')
    test.txt
    

    执行带参数的shell命令

    >>> ls = sh.ls.bake('-al')
    >>> ls('.')
    total 0
    drwxr-xr-x   3 playcrab  staff   102  4 17 22:36 .
    drwxr-xr-x+ 61 playcrab  staff  2074  4 17 22:36 ..
    -rw-r--r--   1 playcrab  staff     0  4 17 22:36 test.txt
    
    >>>
    

    打印结果和类型

    >>> a = sh.ls('.')
    >>> print a
    nihao.txt   test.txt
    
    >>> print type(a)
    <class 'sh.RunningCommand'>
    

    执行shell脚本

    >>> a = sh.Command('/Users/playcrab/nihao/nihao.sh')
    >>> a()
    123
    
    >>>
    

    管道

    >>> a = sh.wc.bake('-l')
    >>> a(sh.ls('/Users/playcrab/nihao/nihao.sh'))
           1
    
    >>>
    
  4. commands模块

    简单获取命令返回值,执行结果

    >>> import commands
    >>> status,output = commands.getstatusoutput('ls')
    >>> print status,output
    0 nihao.sh
    nihao.txt
    test.txt
    

    直接返回执行结果

    >>> commands.getoutput('pwd')
    '/Users/playcrab/nihao'
    

    还有一个getstatus方法,据说已经废掉了,就不介绍了

links

social