通过访问变量从字符串执行脚本?

Execute script from string with accessing the variables?

我有一个 python 脚本作为字符串,例如:

exec("sent = {'test': 1}")
global sent
print(sent)

我使用 exec 函数执行它,然后使用 global python 命令访问变量。这种方式在不使用 classes 的情况下没有问题,但是当我在 class 中使用相同的代码时,例如:

class example:
    def fun1(self):
        exec("sent = {'test': 1}")
        global sent
        print(sent)

v = example()
print(v.fun1())

我收到以下错误:

NameError: name 'sent' is not defined

你真的应该避免使用全局变量。无论如何,方法如下:

class example:
    def fun1(self):
#        globals sent  # Not needed in this special case.
        exec("sent = {}", globals())
        print('in fun1, "sent" is now', sent )


v = example()
print(v.fun1())  # Result will be None because fun1() doesn't return anything.
print('after call to fun1(), global "sent" is', sent)

输出:

in fun1, "sent" is now {}
None
after call to fun1(), global "sent" is {}

global 声明只在函数或 class 方法中做一些事情,即便如此,只有在全局变量的值要被设置为某些东西时才需要。 然而,作为一种特殊情况,在 fun1() 方法中并不真正需要它,因为它在调用 exec() 时显式传递 globals()(但不是单独的本地字典)。无论如何放入一个以使其更清楚发生了什么可能是个好主意。

以这种方式使用 exec() 在其 documentation 中有说明:

If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables.

(强调我的)

这是一种完全避免在方法中引用全局变量的方法:

class example:
    def fun1(self):
        namespace = {}
        exec("sent = {}", namespace)
        sent = namespace['sent']  # Retrieve result.
        print('in fun1, "sent" is now', sent )
        return sent

v = example()
sent = v.fun1()
print('after calling fun1(), "sent" got set to', sent)

输出:

in fun1, "sent" is now {}
after calling fun1(), "sent" got set to {}

您没有通过全局字典进行修改。尝试:

 exec("sent = {}",globals())