在python中从函数名获取函数参数

在python中从函数名获取函数参数,python,function,parameters,Python,Function,Parameters,给定一个函数的名称(作为字符串),我可以得到该函数的参数列表(假设它存在于同一个文件中)吗?基本上,我想要的是: def foo(bar): print str(bar); funcName = 'foo'; printFunctionParameters(funcName); 我显然希望printFunctionParameters打印bar 有什么建议吗?使用检查模块: >>> import inspect >>> def foo(bar):p

给定一个函数的名称(作为字符串),我可以得到该函数的参数列表(假设它存在于同一个文件中)吗?基本上,我想要的是:

def foo(bar):
    print str(bar);

funcName = 'foo';
printFunctionParameters(funcName);
我显然希望
printFunctionParameters
打印
bar


有什么建议吗?

使用
检查
模块:

>>> import inspect
>>> def foo(bar):pass
>>> inspect.getargspec(foo)
ArgSpec(args=['bar'], varargs=None, keywords=None, defaults=None)

使用
检查
模块:

>>> import inspect
>>> def foo(bar):pass
>>> inspect.getargspec(foo)
ArgSpec(args=['bar'], varargs=None, keywords=None, defaults=None)
试试看

import inspect

def foo(bar):pass
inspect.getargspec(eval('foo'))
或者

试试看

import inspect

def foo(bar):pass
inspect.getargspec(eval('foo'))
或者


在Python 3中,不推荐使用
inspect.getargspec()
,您应该使用
inspect.signature()


在Python 3中,不推荐使用
inspect.getargspec()
,您应该使用
inspect.signature()


那不是我想要的。请注意,我只得到一个字符串形式的函数名。有没有办法在字符串上使用inspect?我想出来了。在您的情况下,如果
a='foo'
,那么我所要做的就是使用eval函数和您的建议,即
inspect.getargspec(eval(a))
。请更新您的答案,以便我将其设置为正确。谢谢。不要在这里使用eval,只需访问模块
\uuu dict\uuu
。根据函数是否在当前模块中,使用
inspect.getargspec(module.\uu dict\uu[funcName])
inspect.getargspec(globals()[funcName])
。@Evan感谢您的回复。你的版本也可以。有什么特别的原因让你更喜欢它而不是
eval
?@alguru这不是我想要的。请注意,我只得到一个字符串形式的函数名。有没有办法在字符串上使用inspect?我想出来了。在您的情况下,如果
a='foo'
,那么我所要做的就是使用eval函数和您的建议,即
inspect.getargspec(eval(a))
。请更新您的答案,以便我将其设置为正确。谢谢。不要在这里使用eval,只需访问模块
\uuu dict\uuu
。根据函数是否在当前模块中,使用
inspect.getargspec(module.\uu dict\uu[funcName])
inspect.getargspec(globals()[funcName])
。@Evan感谢您的回复。你的版本也可以。有没有什么具体的原因让你更喜欢它而不是
eval
?@alguru