【问题标题】:Call function with named parameters from dictionary使用字典中的命名参数调用函数
【发布时间】:2017-11-02 12:41:27
【问题描述】:

假设我有这样的功能:

def fun(n, m, verbose=0, use_fib_heap=False):
    '''blah blah'''
    pass

然后我解析命令行参数并尝试按指定运行它:

from sys import argv
opts = dict()
for arg in argv[1:]:
    if arg.startswith('--'):
        if '=' in arg:
            p, v = arg[2:].split('=')[:2]
            opts[p] = v
        else:
            p = arg[2:]
            opts[p] = True

如果我以python3 code.py --verbose=3 --use_fib_heap 运行我的代码,如何调用fun

【问题讨论】:

  • 在脚本末尾定义opts - fun(**opts)?

标签: python python-3.x dictionary arguments


【解决方案1】:

正常调用函数

from sys import argv
opts = dict()
for arg in argv[1:]:
    if arg.startswith('--'):
        if '=' in arg:
            p, v = arg[2:].split('=')[:2]
            opts[p] = v
        else:
            p = arg[2:]
            opts[p] = True
        fun(with_params)

【讨论】:

  • 什么是with_params
猜你喜欢
  • 2015-07-29
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-25
  • 2012-11-05
  • 1970-01-01
  • 2017-09-04
相关资源
最近更新 更多