开发者

Using optparse in Python

开发者 https://www.devze.com 2023-03-07 16:41 出处:网络
Is there a way I can configure optparse in Python to not take开发者_开发技巧 the beginning -? So instead of

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


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.


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号