Skip to content

Instantly share code, notes, and snippets.

@lsevero
Forked from elleryq/command.py
Created February 5, 2018 18:28
Show Gist options
  • Save lsevero/21a9dfa27301c578d4dbd6e3e4c70e0b to your computer and use it in GitHub Desktop.
Save lsevero/21a9dfa27301c578d4dbd6e3e4c70e0b 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