Python: How can I enable use of kwargs when calling from command line? (perhaps with argparse)
<p>suppose I have the module myscript.py; This module is production code, and is called often as <code>%dir%&gt;python myscript.py foo bar</code>. </p>

<p>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 </p>

<p><code>%dir%&gt;python myscript.py main(foo, bar)</code>.</p>

<p>I know that I can use the <code>argparse</code> module, but I'm not sure how to do it. </p>

<pre><code>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:]))
</code></pre>

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

<pre><code>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
</code></pre>

python python-2.7 command-line argparse kwargs