Python sh library learning part 1

The official documentation has a sentence "allows you to call any program", and:
helps you write shell scripts in Python by giving you the good features of Bash
The first sentence helps you easily call your own program in Python, and the second sentence Give you a chance to make friends with local tyrants like Shell

(1) Programs that call the system

  1. >>> import sh
  2. >>> print(sh.ls('/home/mysql'))
  3. cdio_bak.sql mysql-5.5.16.tar.gz
  4. mm percona-xtrabackup-2.1.4-656-Linux-i686.tar.gz
  5. mysql percona-xtrabackup-2.1.4-Linux-i686
  6. mysql-5.5.16 startmysql.sh

(ii) call your own program

  1. >>> import sh
  2. >>> r=sh.Command('/root/dd.py')
  3. >>> r()
  4. hello,DBA

(iii) bake command parameters

  1. >>> import sh
  2. >>> du = sh.du.bake ( '-shc' )
  3. >>> print (du('/home/mysql'))
  4. 1.1G /home/mysql
  5. 1.1 G total

(iv) glob list files

  1. >>> import sh
  2. >>> list=sh.glob('/root/mm/*')
  3. >>> print list
  4. ['/root/mm/Backup', '/root/mm/Usplash', '/root/mm/AWN', '/root/mm/Wallpapers', '/root/mm/GRUB', '/root/mm/Mozilla']

(v) Pipeline

  1. >>> print(sh.sort(sh.du(sh.glob('*'),'-shc'),'-rn'))
  2. 712K distribute-0.6.49.tar.gz
  3. 672K setuptools-1.1.5.tar.gz
  4. 548K get-pip.py

Pipelines are ordered, inside-out by default, but what if parallelism is required? Add a _piped=True 

  1. >>> for line in sh.tr(sh.tail("-f", "/home/mysql/mysql/log/alert.log", _piped=True), "[:upper:]", "[:lower:]", _iter=True):
  2. ... print line
  3. ...
  4. innodb: doublewrite buffer not found: creating new
  5. innodb: doublewrite buffer created
  6. innodb: 127 rollback segment(s) active.
  7. innodb: creating foreign key constraint system tables
  8. innodb: foreign key constraint system tables created



By DBA_WaterBin

2013-09-30

Good Luck

Related: Python sh library learning part 1