Skip to content

Instantly share code, notes, and snippets.

@odoku
Created March 22, 2019 11:27
Show Gist options
  • Save odoku/777c40f472b39e08f72607289710428e to your computer and use it in GitHub Desktop.
Save odoku/777c40f472b39e08f72607289710428e to your computer and use it in GitHub Desktop.
Abstract command wrapper for Python
import subprocess
class Command(object):
def __init__(self, *args, encode='utf8'):
self.encode = encode
self.args = args
def __repr__(self):
return '<Command({})>'.format(' '.join(self.args))
def __getattr__(self, name):
args = self.args + (name,)
return self.__class__(*args)
def __call__(self, *args, **kwargs):
return self.__run(*args, **kwargs)
def __run(self, *args, **kwargs):
cmd = self.__build_cmd(*args, **kwargs)
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=None
)
stdout, stderr = process.communicate()
stdout = stdout.decode(self.encode)
stderr = stderr.decode(self.encode)
if process.returncode != 0:
raise Exception(cmd, process.returncode, (stdout, stderr))
else:
return stdout, stderr
def __build_cmd(self, *args, **kwargs):
options = []
for key, value in kwargs.items():
if value is None:
options.append('--{}'.format(key))
else:
options.append('--{}={}'.format(key, value))
return self.args + args + tuple(options)
ls = Command('ls')
stdout, stderr = ls('-la')
print(stdout,stderr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment