0

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?

2
Contributors
1
Reply
7
Views
5 Years
Discussion Span
Last Post by Gribouillis
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.