How to use getopt in Python

In the past couple months, I have kept running into getopt module of Python in my work code base. I was kind of confused about its usage initially, and I found the Python documentation does not explain it in an explicit way. So I took some time to look into it. Here is what I got.

"getopt" module is used to handle the command line option.For instance, let's say there's a command as below:

./justForSample -c -b 5 --mm --lala /home

For above command, you would get ['./justForSample', '-c','-b','5','--mm', '--lala', '/home'] from sys.argv, while '-c' stands for short option without additional parameter, '-b' stands for short option with additional parameter of '5'; '--mm' stands for long option without additional parameter, and '--lala' stands for long option with additional paramter of '/home'.

The format of getopt function is as below:

getopt.getopt(commandline parameter, "short option",[long option])

If one short option need a parameter, add ":" to the end of that short option, while if one long option need a parameter, add "=" to the end of that long option.

There are two returns from getopt, the first one is the array of the corresponding options and their values, the another one is the output of other command line without used parameters.

So for above command, we should call the getopt as below:

getopt.getopt(sys.argv[1:], 'cb:', ['mm','lala='])

The first return is
[('-c',''),('-b','5', ('--mm',''),('--lala', '/home')] , the another return is empty.

comments powered by Disqus