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:]))
If you want to pass in keyword arguments as you would in the main function, key=value
, you can do it like so:
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) < 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])
Some examples:
$> python my_file.py a b x=4
Called my script with
foo = a
bar = b
Keyword argument: x = 4
$> python my_file.py foo bar key=value
Called my script with
foo = foo
bar = bar
Keyword argument: key = value
However, this assumes that the key and value do not have any whitespace between them, key = value
will not work.
If you are looking for --argument
kinds of keyword arguments, you should use argparse
.