忽略exec中的外部变量



我希望在Python中使用exec命令,这样就不会在其中考虑外部变量。例如:

x=2
exec('print(x)')

现在我希望这段代码获取一个错误,说x没有定义,因为x不在exec命令中。

传递exec一个空的globals字典:

>>> x=2
>>> exec("print(x)")
2
>>> exec("print(x)", {})

NameError: name 'x' is not defined
>>> 

exec的文档:

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.

相关内容

  • 没有找到相关文章

最新更新