官方文档有句话"allows you to call any program",并且:helps you write shell scripts in Python by giving you the good features of Bash第一句话助你在Python中轻松调用自己的程序,第二句则给你机会和Shell这种土豪交朋友
㈠ 调用系统的程序
>>> import sh>>> print(sh.ls('/home/mysql'))cdio_bak.sql mysql-5.5.16.tar.gzmm percona-xtrabackup-2.1.4-656-Linux-i686.tar.gzmysql percona-xtrabackup-2.1.4-Linux-i686mysql-5.5.16 startmysql.sh㈡ 调用自己的程序
>>> import sh>>> r=sh.Command('/root/dd.py')>>> r()hello,DBA㈢ bake命令参数
>>> import sh>>> du=sh.du.bake('-shc')>>> print (du('/home/mysql'))1.1G /home/mysql1.1G 总计㈣ glob列出文件
>>> 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']㈤ 管道
>>> print(sh.sort(sh.du(sh.glob('*'),'-shc'),'-rn'))712K distribute-0.6.49.tar.gz672K setuptools-1.1.5.tar.gz548K get-pip.py管道是有序的,默认由内而外,但如果需要并行呢?加个_piped=True
>>> 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 newinnodb: doublewrite buffer createdinnodb: 127 rollback segment(s) active.innodb: creating foreign key constraint system tablesinnodb: foreign key constraint system tables created
By DBA_WaterBin
2013-09-30
Good Luck