elleryq
2/5/2016 - 7:50 AM

Wrap shell command as python function

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()