문제

What would this piece of code do and what is the role of sys.modules here?:

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)
도움이 되었습니까?

해결책

This code adds all sub directories under current directory (from where script is running) to the path so that any modules can be loaded from it's sub-directories.

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top