这段代码会做什么以及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)
答案 0 :(得分: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