蟒蛇EXEC不采取任何kwargs

问题描述 投票:1回答:2
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功能?

python python-3.x exec
2个回答
2
投票

全局()是存储与节目相关的全球范围内所有变量信息的功能。 (全局符号表)

解决你的需求的一种方法如下:

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

1
投票

正如在评论@ juanpa.arrivillaga提到的,这是一个位置参数:

exec("print(a)", {'a':1})

回报

1
© www.soinside.com 2019 - 2024. All rights reserved.