When creating a command line tool, you quickly are faced with the burden of handling command line arguments (parsing options, arguments, flags, etc). In Python, the optparse module or, its newer version, the argparse module are very nice solutions to build powerful command line interfaces, completely with automatically generated help.

Sometimes however, you just want a quick, simple and small way to get from A to B without a lot of overhead and overkill. Below I'll show you a quick and simple Python trick for command line handling by directly mapping the command line arguments to function arguments.

The beauty lies in letting Python function argument handling do the boring work (argument count checking, falling back on default values), so we don't have to do it:

import sys

def do_something(x, y, z='ZAZAZAZA'):
    print 'x:', x
    print 'y:', y
    print 'z:', z

if __name__ == '__main__':
    # Map command line arguments to function arguments.
    do_something(*sys.argv[1:])

Let's run this with three arguments:

$ python dosomething.py one twoo three
x: one
y: twoo
z: three

Run it with two arguments and Python will assign a default value for the third:

$ python dosomething.py one twoo
x: one
y: twoo
z: ZAZAZAZA

Run it with one, zero, four or more arguments and Python will complain about argument mismatch:

$ python dosomething.py one
Traceback (most recent call last):
  File "./dosomething.py", line 11, in <module>
    do_something(*sys.argv[1:])
TypeError: do_something() takes at least 2 arguments (1 given)

Handy!