2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python subprocess wrapper class

Last updated at Posted at 2013-06-04

バージョン 2.6 で撤廃: commands モジュールは Python 3.0 で削除されました。
代わりに subprocess モジュールを使ってください。

commandsとお別れするためSubprocessをつかってみる。
*シェルインジェクションされないようにする。
* ワンライナー好きな鯖管が直観的に使えるようにする。
*イメージはsqlalchemyのクエリのfilterような感じでPIPEさせる。

shell.py
# !/usr/bin/python

import sys
import shlex
from   subprocess import Popen, PIPE, STDOUT

__version__ = '0.0.1'

# ----------------------------------------------------------
# SHELL CLASS
# ----------------------------------------------------------
class Shell(object):

    def __init__(self):

        self.p  = None

    def cmd(self, cmd):

        p_args = {'stdin'     : None,
                  'stdout'    : PIPE,
                  'stderr'    : STDOUT,
                  'shell'     : False,}

        return self._execute(cmd, p_args)

    def pipe(self, cmd):

        p_args = {'stdin'     : self.p.stdout,
                  'stdout'    : PIPE,
                  'stderr'    : STDOUT,
                  'shell'     : False,}

        return self._execute(cmd, p_args)

    def _execute(self, cmd, p_args):

        try :
            self.p = Popen(shlex.split(cmd), **p_args)
            return self

        except :
            print 'Command Not Found: %s' % (cmd)
            sys.exit()

    def commit(self):

        result = self.p.communicate()[0]
        status = self.p.returncode

        return (status, result)

# ----------------------------------------------------------
# TEST
# ----------------------------------------------------------
def test():
    '''
    tac ./test.txt | sort | uniq -c

    '''
    shell= Shell()

    #--- CASE 1
    (return_code, stdout) = shell.cmd('tac ./test.txt').pipe('sort').pipe('uniq').commit()
    print 'RETURN_CODE: %s  \nSTDOUT: \n%s' % (return_code, stdout)

    #--- CASE 2
    s = shell.cmd('tac ./test.txt')
    s.pipe('sort')
    s.pipe('uniq')
    (return_code, stdout) = s.commit()
    print 'RETURN_CODE: %s, \nSTDOUT: \n%s' % (return_code, stdout)

if __name__ == '__main__':test()
test.txt
1
2
3
4
5
6
7
8
9
0

結果

RETURN_CODE: 0
STDOUT:
0
1
2
3
4
5
6
7
8
9

RETURN_CODE: 0,
STDOUT:
0
1
2
3
4
5
6
7
8
9

結論

方向性は間違えてない気がするがエラー処理がいろいろとおかしい。
そのうちに見直ししてみよう。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?