m5/objects/_init__uuu.py文件gem5中发生了什么

2024-05-31 23:46:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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目录中,只有一个文件“\uuu init\uu.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?中,他们谈到了加载程序的含义,但我觉得我遗漏了一些东西。任何帮助都将不胜感激。提前谢谢


Tags: theinfrompyimportmodulesforobjects
1条回答
网友
1楼 · 发布于 2024-05-31 23:46:10

{}

考虑下面的代码:

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)>

只要在PYTHONPATH中没有名为foo的python模块

Python导入钩子(PEP 302)允许我们自定义import的行为。在上面的示例中,模块foo被称为是由FooImporter找到并处理的。注意导入程序将创建模块foo作为sys的别名。完整的导入器(与我们看到的简化导入器不同)将负责将导入模块的__loader__属性设置为导入器本身

Gem5进口挂钩

回到您的问题,gem5通过其模块化设计使用相同的机制来加载SimObject。您可以在src/python/importer.py找到类名为CodeImporter的导入器类

当模块m5.object被导入时

from m5.objects import Root

CodeImporter将负责处理导入任务,其中将为导入的模块设置__loader__属性(在本例中为m5.objects)。如果您尝试在m5/objects/__init__.py中打印__loader__,您将得到如下结果:

<importer.CodeImporter object at 0x7f4f58941d60>

__loader__.modules是一个包含gem5维护的SimObjects的字典,其中每个项都将由来自src/sim/init.ccaddModule()调用添加

只要一个^ {< CD10>}的C++对应称为{{CD24>}的构造函数,它将被添加到一个列表中,因此GEM5初始化将记住将它添加到^ {CD12>}的实例中。例如,应该能够在注册Root对象的构建文件夹中找到Root.py.cc文件。m5/object/__init__.py末尾的循环只是通过此机制导入已知的SimObject的列表

我认为这应该足以让某人了解潜在的魔法,并(希望)解决他们的好奇心

相关问题 更多 >