What would be an easy expression to process command line arguments if I’m expecting anything like 001 or 999 (let’s limit expectations to 001…999 range for this time), and few other arguments passed, and would like to ignore any unexpected?
I understand if for example I need to find out if ‘debug’ was passed among parameters it’ll be something like that:
if 'debug' in argv[1:]: print 'Will be running in debug mode.'
How to find out if 009 or 575 was passed?
All those are expected calls:
python script.py python script.py 011 python script.py 256 debug python script.py 391 xls python script.py 999 debug pdf
At this point I don’t care about calls like that:
python script.py 001 002 245 568 python script.py some unexpected argument python script.py 0001 python script.py 02
…first one – because of more than one ‘numeric’ argument; second – because of… well, unexpected arguments; third and fourth – because of non-3-digits arguments.
As others answered, optparse is the best option, but if you just want quick code try something like this:
EDIT: Here’s an optparse example because so many people are answering optparse without really explaining why, or explaining what you have to change to make it work.
The primary reason to use optparse is it gives you more flexibility for expansion later, and gives you more flexibility on the command line. In other words, your options can appear in any order and usage messages are generated automatically. However to make it work with optparse you need to change your specifications to put ‘-‘ or ‘–‘ in front of the optional arguments and you need to allow all the arguments to be in any order.
So here’s an example using optparse:
The differences here with optparse and your spec is that now you can have command lines like:
and you can easily add new options by calling parser.add_option()