Thursday, April 30, 2015

Simple Python cmdline argument handling

In Python, there are optparse module and its newer version, the argparse module, to build powerful solutions for command line interfaces.

Here is another simpler way to do the similar way, that handle the argument directly mapping to function arguments.

Below is the script:
#!/usr/bin/python
import sys
def do(x, y, z='zd'):  print 'x:', x  print 'y:', y  print 'z:', z
if __name__ == '__main__':  # Map command line arguments to function arguments.  do(*sys.argv[1:])

Let's pass in with 3 arguments:
$ ./do.py a b cx: ay: bz: c
Let's pass in with 2 arguments:
$ ./do.py a bx: ay: bz: zd
Let's pass in with 4 arguments:
$ ./do.py a b c dTraceback (most recent call last):  File "./do.py", line 12, in <module>    do(*sys.argv[1:])TypeError: do() takes at most 3 arguments (4 given)[1]    23517 exit 1     ./do.py a b c d
Let's pass in with 1 arguments:
$ ./do.py aTraceback (most recent call last):  File "./do.py", line 12, in <module>    do(*sys.argv[1:])TypeError: do() takes at least 2 arguments (1 given)[1]    23536 exit 1     ./do.py a