首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从optparse传递可选参数

从optparse传递可选参数
EN

Stack Overflow用户
提问于 2012-07-26 09:51:44
回答 2查看 1.1K关注 0票数 1

我正在尝试弄清楚如何从optparse传递可选参数。我遇到的问题是,如果没有指定optparse选项,它将缺省为None类型,但如果我将None类型传递给函数,它会对我大喊大叫,而不是使用缺省类型(这是可以理解和有效的)。

代码语言:javascript
复制
conn = psycopg2.connect(database=options.db, hostname=options.hostname, port=options.port)

问题是,如果在没有大量if语句的情况下有输入,我如何使用函数的默认值作为可选参数,但仍然传递用户输入。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-26 10:11:16

定义一个函数remove_none_values,用于过滤字典中的非赋值参数。

代码语言:javascript
复制
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))

或者,定义一个函数包装器,在将数据传递给原始函数之前不删除任何值。

代码语言:javascript
复制
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)
票数 2
EN

Stack Overflow用户

发布于 2014-04-02 16:40:49

我的thebops包(pip install thebopshttps://bitbucket.org/therp/thebops)的opo模块包含一个add_optval_option函数。这使用了一个附加的关键字参数empty,该参数指定了在不带值的情况下使用该选项时要使用的值。如果在命令行中找到一个选项字符串,则将此值注入到参数列表中。

这仍然是一个黑客,但至少它是一个简单易用的函数...

它在以下情况下工作良好:

  • 创建选项时,参数向量确实已经存在。这通常是正确的。
  • 我发现的所有带有可选值的sport参数的程序都需要将给定值附加为--option=value-ovalue,而不是--option value或sport

也许我会调整thebops.optparse以支持empty参数;但我希望首先有一个测试套件来防止回归,最好是原始的Optik / optparse测试。

代码如下:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11661246

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档