Created
February 5, 2016 07:50
-
-
Save elleryq/bb01713553692fc89a99 to your computer and use it in GitHub Desktop.
Wrap shell command as python function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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