猫型エンジニアのブログ

プログラム/ネットワーク系の技術関連をまとめたページです 

Pythonでパイプ付きシェルコマンドの実行

 Pythonのプログラム内部においてシェルコマンドを実行するには、subprocessやos.systemなどいくつか方法があります。その中でももっとも簡単なのがshの利用です。

インストール

pipコマンドでインストールします。

# pip install sh
Downloading/unpacking sh
  Downloading sh-1.09.tar.gz
  Running setup.py egg_info for package sh

Installing collected packages: sh
  Running setup.py install for sh

Successfully installed sh
Cleaning up...

パイプを含まないシェルコマンドの実行

sh."実行したいコマンド"(引数1,引数2...)

のような使い方です。
"ls -l /var"コマンドは以下のように実行します。

# python
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sh
>>> print(sh.ls("/var", "-l"))
total 44
drwxr-xr-x  2 root root     4096  3月 21 00:39 backups
drwxr-xr-x 19 root root     4096 12月 26 03:35 cache
drwxrwsrwt  2 root whoopsie 4096  2月  6 07:35 crash
(以下略)

パイプを含むシェルコマンドの実行

コマンドを引数の中に入れ子にすることで、パイプとして動作します。
"ls -l /etc |grep wc -l"コマンドは以下のようにして実行します。

# python
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sh
>>> print(sh.wc(sh.ls("/etc", "-l"),"-l"))
243

簡単ですね!