gpt4 book ai didi

python - m5/objects/__init__.py 文件 gem5 中发生了什么

转载 作者:行者123 更新时间:2023-12-04 09:25:44 24 4
gpt4 key购买 nike

我是 gem5 模拟器的新手。我正在阅读文档(http://www.m5sim.org/Configuration_/_Simulation_Scripts),试图了解一切是如何实现的。当他们写 Python 类时,他们会说:

gem5 provides a collection of Python object classes that correspond to its C++ simulation object classes. These Python classes are defined in a Python module called "m5.objects". The Python class definitions for these objects can be found in .py files in src, typically in the same directory as their C++ definitions.


To make the Python classes visible, the configuration file must first import the class definitions from the m5 module


在 m5/objects 目录中只有一个文件“__init__.py”。这是代码:
from __future__ import print_function
from __future__ import absolute_import

from m5.internal import params
from m5.SimObject import *

try:
modules = __loader__.modules
except NameError:
modules = { }

for module in modules.keys():
if module.startswith('m5.objects.'):
exec("from %s import *" % module)
通常我不使用 Python 编程,所以也许这就是问题所在,但我还没有完全理解这里发生了什么。在这篇文章中 Python's __loader__, what is it?他们谈论什么 装载机 意思是,但我觉得我错过了一些东西。任何帮助,将不胜感激。提前致谢。

最佳答案

__loader__考虑以下代码:

import sys
class FooImporter:
def find_module(self, module_name, package_path):
return self if module_name == 'foo' else None

def load_module(self, module_name):
print('FooImporter is working.')
sys.modules[module_name] = __import__('sys')

# This activates the importer
sys.meta_path.append(FooImporter())
# This should trigger our importer to import 'foo'
import foo
# Show what we've just got
print(foo)
这将导致输出:
FooImporter is working.
<module 'sys' (built-in)>
只要你没有名为 foo 的 python 模块在 PYTHONPATH .
Python Import Hook ( PEP 302 ) 允许我们自定义 import 的行为.在上面的例子中,模块 foo据说是由 FooImporter 找到并处理的.请注意,导入器将创建模块 foo作为 sys 的别名.完整的导入器(与我们看到的简化版不同)将负责设置 __loader__导入模块的属性到导入器本身。
Gem5 的导入钩子(Hook)
回到你的问题,gem5 使用相同的机制来加载 SimObject是通过其模块化设计的。您可以在 src/python/importer.py 找到非常重要的导入器类。类名 CodeImporter .
当模块 m5.object正在进口,比如说,
from m5.objects import Root
CodeImporter将负责处理导入任务,其中 __loader__将为导入的模块设置属性(在本例中为 m5.objects )。如果您尝试打印 __loader__m5/objects/__init__.py ,你会得到类似的东西:
<importer.CodeImporter object at 0x7f4f58941d60>
__loader__.modules是包含 gem5 维护的字典 SimObjects其中每个项目将由 addModule() 添加来自 src/sim/init.cc 的电话.
只要一个 SimObject的 C++ 对应调用了 EmbeddedPython 的构造函数,它将被添加到一个列表中,因此 gem5 初始化将记住将其添加到 CodeImporter 的实例中.例如,应该能够找到 Root.py.cc注册 Root 的构建文件夹中的文件目的。 m5/object/__init__.py结尾的循环只是导入已知 SimObject 的列表是通过这种机制。
我认为这应该足以让某人了解潜在的魔法并(希望)解决他们的好奇心。

关于python - m5/objects/__init__.py 文件 gem5 中发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63018861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com