gpt4 book ai didi

python - 如何使用 argparse 参数作为函数名

转载 作者:太空狗 更新时间:2023-10-30 02:30:00 25 4
gpt4 key购买 nike

我想实现 Argparse 介绍中的示例:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

但就我而言,我希望有更多可能的函数名称可供选择。

def a(): ...
def b(): ...
def c(): ...

parser.add_argument('-f', '--func',
choices=[a, b, c],
required=True,
help="""Choose one of the specified function to be run.""")
parser.func()

像那样使用它并没有按预期工作,我明白了

$ python program.py -f=a
program.py: error: argument -f/--func: invalid choice: 'a' (choose from
<function a at 0x7fa15f32f5f0>,
<function b at 0x7fa15f32faa0>,
<function c at 0x7ff1967099b0>)

我知道我可以使用基本的字符串参数和流控制来解决它,但如果我可以直接将解析器参数用作函数名称,它会变得不那么困惑并且更容易维护。

最佳答案

您可以使用基本的字符串参数,并通过使用 dict 从名称中获取实际函数来最大限度地减少困惑。

我在 Python 2.6.6 上,所以我不能使用 argparse,但是这段代码应该给你大致的想法:

#!/usr/bin/env python

def a(): return 'function a'
def b(): return 'function b'
def c(): return 'function c'

func_list = [a, b, c]
func_names = [f.func_name for f in func_list]
funcs_dict = dict(zip(func_names, func_list))

f = funcs_dict['b']
print f()

输出

function b

因此您可以将 func_names 传递给 argparse 并使用 funcs_dict 紧凑地检索所需的函数。


在较新的 Python 版本中,您应该使用 f.__name__ 而不是 f.func_name。 (这也适用于 Python 2.6,但我在写这个答案时不熟悉更新的语法)。

关于python - 如何使用 argparse 参数作为函数名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29653353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com