zoukankan      html  css  js  c++  java
  • Python sh模块--------替换subprocess的利器

    官方文档有句话"allows you to call any program",并且:

    helps you write shell scripts in Python by giving you the good features of Bash
    第一句话助你在Python中轻松调用自己的程序,第二句则给你机会和Shell这种土豪交朋友
     
    ㈠ 调用系统的程序
    [python]  
    >>> import sh  
    >>> print(sh.ls('/home/mysql'))  
    cdio_bak.sql  mysql-5.5.16.tar.gz  
    mm        percona-xtrabackup-2.1.4-656-Linux-i686.tar.gz  
    mysql         percona-xtrabackup-2.1.4-Linux-i686  
    mysql-5.5.16  startmysql.sh  
     
    ㈡ 调用自己的程序
    [python]  
    >>> import sh  
    >>> r=sh.Command('/root/dd.py')  
    >>> r()  
    hello,DBA  
     
    ㈢ bake命令参数
    [python]  
    >>> import sh  
    >>> du=sh.du.bake('-shc')  
    >>> print (du('/home/mysql'))  
    1.1G    /home/mysql  
    1.1G    总计  
     
    ㈣ glob列出文件
    [python]  
    >>> import sh  
    >>> list=sh.glob('/root/mm/*')  
    >>> print list  
    ['/root/mm/Backup', '/root/mm/Usplash', '/root/mm/AWN', '/root/mm/Wallpapers', '/root/mm/GRUB', '/root/mm/Mozilla']  
     
    ㈤ 管道
    [python]  
    >>> print(sh.sort(sh.du(sh.glob('*'),'-shc'),'-rn'))  
    712K    distribute-0.6.49.tar.gz  
    672K    setuptools-1.1.5.tar.gz  
    548K    get-pip.py  
     
    管道是有序的,默认由内而外,但如果需要并行呢?加个_piped=True 
    [python]  
    >>> for line in sh.tr(sh.tail("-f", "/home/mysql/mysql/log/alert.log", _piped=True), "[:upper:]", "[:lower:]", _iter=True):  
    ...   print line  
    ...   
    innodb: doublewrite buffer not found: creating new  
      
    innodb: doublewrite buffer created  
      
    innodb: 127 rollback segment(s) active.  
      
    innodb: creating foreign key constraint system tables  
      
    innodb: foreign key constraint system tables created  
  • 相关阅读:
    【MySQL】JSON相关
    【Scala】01 基础了解
    【Windows】更改Win10字体和Cmd字体
    【DataBase】MySQL根据父节点查询下面的所有子节点
    【Windows】Win10 20H2版本 管理员身份问题
    【Java】树状节点结构的数据
    【Vue】接口模块化处理
    【Server
    【Binary】XShell6 无法使用的解决办法
    【Java】逻辑错误BUG
  • 原文地址:https://www.cnblogs.com/wt11/p/6417466.html
Copyright © 2011-2022 走看看