Skip to content

Instantly share code, notes, and snippets.

@elleryq
Created February 5, 2016 07:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save elleryq/bb01713553692fc89a99 to your computer and use it in GitHub Desktop.
Save elleryq/bb01713553692fc89a99 to your computer and use it in GitHub Desktop.
Wrap shell command as python function
# -*- encoding: utf-8 -*-
import subprocess
class command(object):
def __init__(self, cmd):
self._cmd = cmd
def __call__(self, *args, **kwargs):
cmd = [self._cmd]
for k, v in kwargs.items():
k = k.replace('_', '-')
cmd.append(k)
if v:
cmd.append(v)
if args:
cmd.extend(args)
return subprocess.check_output(cmd)
def main():
# declare ls
ls = command('ls')
print(ls(_l='', _a=''))
# declare ansible
ansible = command('ansible')
# ansible -m ping -i 192.168.1.1, all
args = ['all']
print(ansible(*args, _m='ping', _i='192.168.1.1,'))
# ansible -m ping -i 192.168.1.1, all
print(ansible('all', _m='ping', _i='192.168.1.1,'))
# uname -r
print(command('uname')(_r=''))
# python --version
print(command('python')(__version=''))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment