Deprecated in version 2.6: The commands module has been removed in Python 3.0. Use the subprocess module instead.
Try using Subprocess to say goodbye to commands.
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
result
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
Conclusion
I don't think I'm in the wrong direction, but the error handling is strange. Let's review it soon.
Recommended Posts