简体   繁体   English

python中的optparse

[英]optparse in python

Is there a way I can configure optparse in python to not take the beginning - ? 有没有一种方法可以在python中配置optparse而不以-开始? 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, eg -x or -F. 传统的Unix语法是连字符(“-”),后跟一个字母,例如-x或-F。 Also, traditional Unix syntax allows multiple options to be merged into a single argument, eg -x -F is equivalent to -xF. 同样,传统的Unix语法允许将多个选项合并到单个参数中,例如-x -F等效于-xF。 The GNU project introduced -- followed by a series of hyphen-separated words, eg --file or --dry-run. 引入了GNU项目-之后是一系列连字符分隔的单词,例如--file或--dry-run。 These are the only two option syntaxes provided by optparse. 这是optparse提供的仅有的两个选项语法。

http://docs.python.org/library/optparse.html#terminology 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. parse_args()允许您提供自己的参数列表,而不仅仅是使用sys.argv[1:] (默认情况下会使用它)。 So you could preprocess the commandline arguments, and then pass them to optargs. 因此,您可以预处理命令行参数,然后将其传递给optargs。 Assuming you want all 1-character arguments to count as option keys: 假设您希望所有1个字符的参数都计为选项键:

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) (您也可以将OptionParser子类OptionParser并放在那里)

You may be able to force with use callback action: 您也许可以使用use回调操作强制执行:

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

which gives you raw access to left and right args 这使您可以原始访问左右参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM