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>If you want to pass in keyword arguments as you would in the main function, <code>key=value</code>, you can do it like so:</p>

<pre><code>import sys

def main(foo, bar, *args):
    print "Called my script with"

    print "foo = %s" % foo
    print "bar = %s" % bar

    for arg in args:
        k = arg.split("=")[0]
        v = arg.split("=")[1]

        print "Keyword argument: %s = %s" % (k, v)


if __name__ == "__main__":
    if len(sys.argv) &lt; 3:
        raise SyntaxError("Insufficient arguments.")
    if len(sys.argv) != 3:
        # If there are keyword arguments
        main(sys.argv[1], sys.argv[2], *sys.argv[3:])
    else:
        # If there are no keyword arguments
        main(sys.argv[1], sys.argv[2])
</code></pre>

<p>Some examples:</p>

<pre><code>$&gt; python my_file.py a b x=4
Called my script with
foo = a
bar = b
Keyword argument: x = 4
$&gt; python my_file.py foo bar key=value
Called my script with
foo = foo
bar = bar
Keyword argument: key = value
</code></pre>

<p>However, this assumes that the key and value do not have any whitespace between them, <code>key = value</code> will not work.</p>

<p>If you are looking for <code>--argument</code> kinds of keyword arguments, you <strong>should</strong> use <code>argparse</code>.</p>

python python-2.7 command-line argparse kwargs