如何使用 sys.modules?

0 投票
1 回答
2059 浏览
提问于 2025-04-17 20:21

这段代码会做什么,以及sys.modules在这里的作用是什么呢?

this_dir = os.path.dirname(__file__) 
dir_list = (x for x in os.listdir(this_dir) if os.path.isdir(os.path.join(this_dir, x)))

for dirpath in dir_list:
    if dirpath not in project_path:
        project_path.append(os.path.join(this_dir, dirpath))
setattr(sys.modules[__name__], '__path__', project_path)

1 个回答

1

这段代码会把当前目录下的所有子目录都添加到路径中,这样就可以从这些子目录里加载任何模块了。

import os,sys
this_dir = os.path.dirname(__file__)  #get the current directory of running script
dir_list = (x for x in os.listdir(this_dir) if os.path.isdir(os.path.join(this_dir, x)))     #get the list of directories under current directory 
project_path = []
for dirpath in dir_list:   
    if dirpath not in project_path:
        project_path.append(os.path.join(this_dir, dirpath))
setattr(sys.modules[__name__], '__path__', project_path) #add to sys modules so any modules can be imported from thsi directories

撰写回答