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
我应该如何将额外的参数传递给 python exec
函数?
最佳答案
globals() 是一个函数,它存储与程序的全局范围变量相关的所有信息。 (全局符号表)
解决您的要求的方法如下:
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
关于python exec 没有 kwargs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54538763/