@Ivo Wetzel的回答适用于一行代码中进行函数调用的情况,例如
e = 1 + 7
c = 3
foo(e, 100, b=c)
如果函数调用不在一行中,例如:
e = 1 + 7
c = 3
foo(e,
1000,
b = c)
下面的代码可以工作:
import inspect, ast
def foo(a, f, b):
frame = inspect.currentframe()
frame = inspect.getouterframes(frame)[1]
string = inspect.findsource(frame[0])[0]
nodes = ast.parse(''.join(string))
i_expr = -1
for (i, node) in enumerate(nodes.body):
if hasattr(node, 'value') and isinstance(node.value, ast.Call)
and hasattr(node.value.func, 'id') and node.value.func.id == 'foo'
i_expr = i
break
i_expr_next = min(i_expr + 1, len(nodes.body)-1)
lineno_start = nodes.body[i_expr].lineno
lineno_end = nodes.body[i_expr_next].lineno if i_expr_next != i_expr else len(string)
str_func_call = ''.join([i.strip() for i in string[lineno_start - 1: lineno_end]])
params = str_func_call[str_func_call.find('(') + 1:-1].split(',')
print(params)
您将获得:
[u'e', u'1000', u'b = c']
但是,这仍然可能会出现问题。