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>First, you won't be passing an arbitrary Python expression as an argument. It's brittle and unsafe.</p>

<p>To set up the argument parser, you define the arguments you want, then parse them to produce a <code>Namespace</code> object that contains the information specified by the command line call.</p>

<pre><code>import argparse
p = argparse.ArgumentParser()
p.add_argument('foo')
p.add_argument('bar')
p.add_argument('--add-feature-a', dest='a', action='store_true', default=False)
</code></pre>

<p>In your <code>__main__</code> block, you'll parse the arguments, then pass a dictionary produced from the <code>Namespace</code> to <code>main</code>.</p>

<pre><code>if __name__ == '__main__':
    args = p.parse_args()
    main(**vars(args))
</code></pre>

<p>Then you'll call your script with a line like</p>

<pre><code># foo = "3", bar = "6", a = True
python myscript.py 3 6 --add-feature-a
</code></pre>

<p>or</p>

<pre><code># foo = "moo", bar="7.7", a = False
python myscript.py moo 7.7
</code></pre>

<p>There's a lot more you can do with <code>argparse</code>, but this is a simple example for getting the value it produces into <code>main</code>.</p>

python python-2.7 command-line argparse kwargs