我正在尝试弄清楚如何从optparse传递可选参数。我遇到的问题是,如果没有指定optparse选项,它将缺省为None类型,但如果我将None类型传递给函数,它会对我大喊大叫,而不是使用缺省类型(这是可以理解和有效的)。
conn = psycopg2.connect(database=options.db, hostname=options.hostname, port=options.port)问题是,如果在没有大量if语句的情况下有输入,我如何使用函数的默认值作为可选参数,但仍然传递用户输入。
发布于 2012-07-26 10:11:16
定义一个函数remove_none_values,用于过滤字典中的非赋值参数。
def remove_none_values(d):
return dict((k,v) for (k,v) in d.iteritems() if not v is None)
kwargs = {
'database': options.db,
'hostname': options.hostname,
...
}
conn = psycopg2.connect(**remove_none_values(kwargs))或者,定义一个函数包装器,在将数据传递给原始函数之前不删除任何值。
def ignore_none_valued_kwargs(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
newkwargs = dict((k,v) for (k,v) in d.iteritems() if not v is None)
return f(*args, **kwargs)
return wrapper
my_connect = ignore_none_valued_kwargs(psycopg2)
conn = my_connect(database=options.db, hostname=options.hostname, port=options.port)发布于 2014-04-02 16:40:49
我的thebops包(pip install thebops,https://bitbucket.org/therp/thebops)的opo模块包含一个add_optval_option函数。这使用了一个附加的关键字参数empty,该参数指定了在不带值的情况下使用该选项时要使用的值。如果在命令行中找到一个选项字符串,则将此值注入到参数列表中。
这仍然是一个黑客,但至少它是一个简单易用的函数...
它在以下情况下工作良好:
--option=value或-ovalue,而不是--option value或sport也许我会调整thebops.optparse以支持empty参数;但我希望首先有一个测试套件来防止回归,最好是原始的Optik / optparse测试。
代码如下:
from sys import argv
def add_optval_option(pog, *args, **kwargs):
"""
Add an option which can be specified without a value;
in this case, the value (if given) must be contained
in the same argument as seen by the shell,
i.e.:
--option=VALUE, --option will work;
--option VALUE will *not* work
Arguments:
pog -- parser or group
empty -- the value to use when used without a value
Note:
If you specify a short option string as well, the syntax given by the
help will be wrong; -oVALUE will be supported, -o VALUE will not!
Thus it might be wise to create a separate option for the short
option strings (in a "hidden" group which isn't added to the parser after
being populated) and just mention it in the help string.
"""
if 'empty' in kwargs:
empty_val = kwargs.pop('empty')
# in this case it's a good idea to have a <default> value; this can be
# given by another option with the same <dest>, though
for i in range(1, len(argv)):
a = argv[i]
if a == '--':
break
if a in args:
argv.insert(i+1, empty_val)
break
pog.add_option(*args, **kwargs)https://stackoverflow.com/questions/11661246
复制相似问题