2

Is there a way I can configure optparse in Python to not take the beginning -? So instead of

%program -d optionvalue

I get

%program d optionvalue

Currently, when I try to do

parser.add_option('d', '--database')

i get the following error:

optparse.OptionError: invalid option string 'd': must be at least two characters long

Any help would be appreciated! Thanks

1
  • 1
    Why do you want to do this? That is breaking convention. How are you going to distinguish between argument d and value d? (e.g. program d d) Commented May 20, 2011 at 2:26

3 Answers 3

6

In short, no.

an argument used to supply extra information to guide or customize the execution of a program. There are many different syntaxes for options; the traditional Unix syntax is a hyphen (“-“) followed by a single letter, e.g. -x or -F. Also, traditional Unix syntax allows multiple options to be merged into a single argument, e.g. -x -F is equivalent to -xF. The GNU project introduced -- followed by a series of hyphen-separated words, e.g. --file or --dry-run. These are the only two option syntaxes provided by optparse.

http://docs.python.org/library/optparse.html#terminology

You would have to parse that yourself.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, seems that even 'XX' doesnt work as I get the following error: optparse.OptionError: invalid short option string 'dd': must be of the form -x, (x any non-dash char)
1

parse_args() allows you to provide your own argument list, not just using sys.argv[1:], which it uses by default. So you could preprocess the commandline arguments, and then pass them to optargs. Assuming you want all 1-character arguments to count as option keys:

orig_args = sys.argv[1:]
new_args = []
for arg in orig_args:
    if len(arg) == 1:
        arg = '-' + arg
    new_args.append(arg)

(options, args) = parser.parse_args(new_args)

(you could also subclass OptionParser and put it there)

Comments

0

You may be able to force with use callback action:

http://docs.python.org/library/optparse.html#callback-example-6-variable-arguments

which gives you raw access to left and right args

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.