Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用argparse参数作为函数名_Python_Argparse - Fatal编程技术网

Python 如何使用argparse参数作为函数名

Python 如何使用argparse参数作为函数名,python,argparse,Python,Argparse,我想实现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_argumen

我想实现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>)
$python program.py-f=a
program.py:错误:参数-f/--func:无效选择:“a”(从中选择)
, 
, 
)

我知道我可以用基本的字符串参数和流控制来解决这个问题,但是如果我可以直接使用解析器参数作为函数名,那么就不会那么混乱,也更容易维护。

您可以使用基本的字符串参数,并通过使用
dict
从函数名中获取实际的函数来最小化混乱

我使用的是Python2.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\u name
传递给
argparse
,并使用
func\u dict
紧凑地检索所需函数



在较新的Python版本中,应该使用
f.\uu name\uu
而不是
f.func\u name
。(这在Python2.6中也适用,但我在编写此答案时不熟悉较新的语法)。

您需要确保您的
选项是字符串(用户不能在命令行上输入Python函数对象)。可以使用字典将这些字符串解析为函数。例如:

# Example functions:
def a(i):
    return i + 1
def b(i):
    return i + 2
def c(i):
    return i + 3

# a dictionary mapping strings of function names to function objects:
funcs = {'a': a, 'b': b, 'c': c}

# Add the -f/--func argument: valid choices are function _names_
parser.add_argument('-f', '--func', dest='func',
                     choices=['a', 'b', 'c'], 
                     required=True,
                     help="""Choose one of the specified function to be run.""")

args = parser.parse_args()

# Resolve the chosen function object using its name:    
chosen_func = funcs[args.func]

我的分析可能会出错,但这是我的理解

ArgParse允许您通过强制转换机制从命令行参数创建多个简单对象。 如果传递字符串“5”并指定正在等待整数,则可以获得数字5

实际上,您正试图从字符串“a”中获取一个函数。没有铸造方法可以做到这一点。这是我解决您问题的建议:

import argparse
def foo():
打印(“称为foo”)
def bar():
打印(“称为条”)
函数=[foo,bar]#在这里列出你的函数
函数={function.\uuuu name\uuuuu:函数中函数的函数}
parser=argparse.ArgumentParser()
parser.add_参数('-f','-func',,
选项=列表(functions.keys()),
必需=真,
help=“”选择要运行的指定函数之一。“)
args=parser.parse_args()
函数[args.func]()

现在,您只需在开始时将函数注册到te list函数中,并在最后一行调用它们,这要感谢函数索引,该索引是根据函数列表构建的,并自动替换函数列表

,但函数名称不是函数。它们是弦<[a,b,c]
中的“a”是
False