Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:]))
like image 495
Dr. John A Zoidberg Avatar asked Sep 08 '16 12:09

Dr. John A Zoidberg


1 Answers

@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
like image 71
user94559 Avatar answered Oct 21 '22 00:10

user94559