Python exec() 后找不到执行的函数

Python cannot find the executed function after exec()

执行完了也找不到执行的函数

这是函数:

# function illustrating how exec() functions.
def exec_code():
    LOC = """ 
def factorial(num): 
    fact=1 
    for i in range(1,num+1): 
        fact = fact*i 
    return fact 
print(factorial(5)) 
"""
    exec(LOC) 
    print(factorial)

# Driver Code 
exec_code() 

但是,这会产生错误:

NameError                                 Traceback (most recent call last)
<ipython-input-10-d403750cbbfb> in <module>
     13 
     14 # Driver Code
---> 15 exec_code()

<ipython-input-10-d403750cbbfb> in exec_code()
     10 """
     11     exec(LOC)
---> 12     print(factorial)
     13 
     14 # Driver Code

NameError: name 'factorial' is not defined

我真的很想像上面的模式那样执行一个字符串函数。有谁知道如何解决它?如果不推荐exec,还有其他解决办法吗?

根据 exec(object[, globals[, locals]])

的文档

https://docs.python.org/3/library/functions.html#exec

Note The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.


因此,您需要将自己的本地字典作为全局变量和本地变量传入:

mylocals = {}
exec(your_code, mylocals, mylocals)

然后就可以通过mylocals调用了:

print(mylocals['factorial']())

您可以将 globals() 传递给 exec 调用,使其将函数添加到当前模块:

exec(LOC,globals())