Is it possible to have an optional command-line argument? For example, I want:

script.py -b

to behave differently than

script.py -b 6

In script.py, an enumerated -b argument specifies a behaviour, but if no argument is specified, a behaviour is randomly chosen.

Here is my experimentation with getopt. With an enumerated argument, this works perfectly:

>>> import getopt
>>> my_args = '-a -b BeastieBoys -c InterGalacticPlanetary'.split()
>>> my_args
['-a', '-b', 'BeastieBoys', '-c', 'InterGalacticPlanetary']
>>> optlist, args = getopt.getopt(my_args, 'ab:c:')
>>> optlist
[('-a', ''), ('-b', 'BeastieBoys'), ('-c', 'InterGalacticPlanetary')]

But if an argument is not specified for -b, then the next opt gets pulled in as the argument.

>>> import getopt
>>> my_args = '-a -b -c InterGalacticPlanetary'.split()
>>> my_args
['-a', '-b', '-c', 'InterGalacticPlanetary']
>>> optlist, args = getopt.getopt(my_args, 'ab:c:')
>>> optlist
[('-a', ''), ('-b', '-c')]

Is there any way to mark an option as having arguments optionally?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.