Python의 하위 디렉토리에서 *를 가져올 수 없음 [중복]

Oct 26 2020

하위 디렉터리의 모듈 집합을 상위 디렉터리의 단일 기본 모듈로 가져 오려고합니다.

계획/

main.py
subdirectory/
    __init__.py
    timer.py
    example.py

다음과 같이 개별 .py 파일을 요청할 수 있습니다.

from subdirectory import timer.py

하지만 다음 명령을 실행하면

from subdirectory import *

해당 하위 디렉토리 내에서 모듈을 사용하려고하면 다음 오류가 발생합니다.

File "My:\Path\Here\...", line 33, in main
t = timer.timer()
NameError: name 'timer' is not defined

두 개의 모듈을 가져 오므로 모든 파일을 한 번에 가져올 수 있기를 원합니다. 이미 빈 init .py 파일을 하위 디렉토리에 추가했습니다 . 내가 놓친 것이 있습니까?

답변

3 Selcuk Oct 26 2020 at 06:42

__all__에서 사용하여 모듈 이름을 선언해야 합니다 __init__.py.

__init__.py:

__all__ = ["timer", "example"]

이 동작은 문서화되어 있습니다 .

유일한 해결책은 패키지 작성자가 패키지의 명시 적 색인을 제공하는 것입니다. 이 import명령문은 다음 규칙을 사용합니다. 패키지의 __init__.py코드가라는 목록을 정의하는 __all__경우 from package import *발견 될 때 가져와야하는 모듈 이름 목록으로 간주 됩니다.

2 AndréC.Andersen Oct 26 2020 at 06:48

가져 오기만 작동 subdirectory/__init__.py하게하려면 다음 내용 을 추가하십시오 .

from * import example
from * import timer

그러나 임의의 수의 (이전 및 새) 모듈에 대해이 작업을 수행하려는 경우이 대답 이 원하는 것일 수 있다고 생각 합니다 .

다음 구조로 시작합니다.

main.py
subdirectory/
subdirectory/__init__.py
subdirectory/example.py
subdirectory/timer.py

에서 그런 수입 모두 subdirectory에서 main.py:

from subdirectory import *
t = timer.timer()

그런 다음 subdirectory/__init__.py모듈에 다음을 추가하십시오 .

from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not 
f.endswith('__init__.py')]

그리고 완전성을 위해 subdirectory/timer.py모듈 :

def timer():
    return 42
Deep_Thoughts Oct 26 2020 at 06:34

수입품은 이렇게갑니다.

# if you have timer.py, import it as 
import timer

__init__.py하위 디렉토리에 추가해보십시오 . 이제 다음과 같이 표시됩니다.

계획/


    main.py
    subdirectory/
                 __init__.py
                 timer.py
                 example.py

작동하지 않는 경우 : main.py추가

import sys
sys.path.append("path/to/subdirectory") # replace with the path
import timer