Ordered options in Python's optparse

424 views Asked by At

First of all, I know optparse is deprecated since version 2.7, but I only have Python 2.3 available in the machine I'm working.

The question is how to know the order in which the options were given in the command line, for instance:

python example.py -f foo -b bar

will execute first the option f and then the option b and

python example.py -b bar -f foo

will do the opposite.

The only solution I came up with after reading optargs documentation is to use the callback action to store the option and detect the position relative to the other options, since the options object doesn't seem to follow any particular order.

Do you know another (maybe better) solution to this problem?

1

There are 1 answers

1
kefeizhou On BEST ANSWER

It's against convention to have option flags that trigger different behaviors depending on the order. But if you really want check for the order, you can just look in sys.argv

#assuming both -f and -b are given in cmdline and you need to check for order
index_f = sys.argv.find("-f")
index_b = sys.argv.find("-b")
if index_f < index_b: 
    # do something if -f is before -b