help(exec)
给我
Help on built-in function exec in module builtins:
exec(source, globals=None, locals=None, /)
Execute the given source in the context of globals and locals.
The source may be a string representing one or more Python statements
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
虽然
>>> exec("print(a)", globals={'a':1})
给我
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: exec() takes no keyword arguments
我应该如何传递额外的参数给蟒蛇exec
功能?
全局()是存储与节目相关的全球范围内所有变量信息的功能。 (全局符号表)
解决你的需求的一种方法如下:
In [1]: a = 1
In [2]: exec("print(a)", globals())
1
或者,如果你想使用kwargs
,那么它应该是一个函数如下:
In [1]: def val_a():
...: return 10
In [2]: exec("print(a)", {'a': val_a()})
10
正如在评论@ juanpa.arrivillaga提到的,这是一个位置参数:
exec("print(a)", {'a':1})
回报
1