我正在运行一个 websocket python 文件。在那,我使用 imp 模块在函数中创建了内置模块,并且我正在另一个函数中使用 exec() 执行字符串函数。 我在 exec() 中使用这些内置模块作为 globals 参数。 但是当我在string的函数中使用这些模块时,它会抛出以下错误
'module' object has no attribute 'pose'
但是,在 string 函数之外使用这些模块可以完美工作并返回预期值。 但是如何在函数内部使用呢?.
这是完整的代码
import imp
import sys
import time
def generate_modules():
destination_module = imp.new_module("destination")
destination_module.destination = imp.new_module("destination")
destination_module.destination.pose = "Hello World"
# Define GUI module
gui_module = imp.new_module("GUI")
gui_module.GUI = imp.new_module("GUI")
gui_module.GUI.robotPose = lambda: "robotPose"
sys.modules["destination"] = destination_module
sys.modules["GUI"] = gui_module
return gui_module,destination_module
#Main function
def process_code():
gui_module,destination_module = generate_modules()
builtin_modules = {"GUI": gui_module,"destination":destination_module,"time": time}
globl = globals()
global_functions = globl.copy()
global_functions.update(builtin_modules)
sequential_code = """from GUI import GUI
from destination import destination
def generatepath():
data = destination.pose
pose = GUI.robotPose()
return data"""
dic = {}
exec(sequential_code,global_functions,dic)
func = dic["generatepath"]
value = func()
return value
process_code()
谢谢,感谢您的帮助
答案 0 :(得分:0)
如果 exec 获取两个单独的对象作为全局对象和本地对象,则代码将被执行,就像它嵌入在类定义中一样。
值得注意的是,members of a class scope are not visible inside any nested scope. 由 from destination import destination
产生的别名仅在顶级作用域中可见,在函数内部不可见。
一个简单的解决方案是省略 locals 字典:
...
exec(sequential_code,global_functions)
func = global_functions["generatepath"]
...