Python: How can I enable use of kwargs when calling from command line? (perhaps with argparse)

Dr. John A Zoidberg picture Dr. John A Zoidberg · Sep 8, 2016 · Viewed 22.7k times · Source

suppose I have the module myscript.py; This module is production code, and is called often as %dir%>python myscript.py foo bar.

I want to extend it to take keyword arguments. I know that I can take these arguments using the script below, but unfortunately one would have to call it using

%dir%>python myscript.py main(foo, bar).

I know that I can use the argparse module, but I'm not sure how to do it.

import sys

def main(foo,bar,**kwargs):
    print 'Called myscript with:'
        print 'foo = %s' % foo
        print 'bar = %s' % bar
        if kwargs:
            for k in kwargs.keys():
                print 'keyword argument : %s' % k + ' = ' + '%s' % kwargs[k]   

if __name__=="__main__":
    exec(''.join(sys.argv[1:]))

Answer

user94559 picture user94559 · Sep 8, 2016

@Moon beat me to it with a similar solution, but I'd suggest doing the parsing beforehand and passing in actual kwargs:

import sys

def main(foo, bar, **kwargs):
    print('Called myscript with:')
    print('foo = {}'.format(foo))
    print('bar = {}'.format(bar))
    for k, v in kwargs.items():
        print('keyword argument: {} = {}'.format(k, v))

if __name__=='__main__':
    main(sys.argv[1], # foo
         sys.argv[2], # bar
         **dict(arg.split('=') for arg in sys.argv[3:])) # kwargs

# Example use:
# $ python myscript.py foo bar hello=world 'with spaces'='a value'
# Called myscript with:
# foo = foo
# bar = bar
# keyword argument: hello = world
# keyword argument: with spaces = a value