문제

런타임에 Python 코드는 내가 모르는 부하에 서브 모듈의 이름을 가져옵니다. 이제이 서브 모듈이 기존 모듈에있는 경우 확인하고 싶습니다. foobar를 지정할 수있는이 구조를 고려하십시오.

master/
|
|- __init__.py
|
|- foo/
|  |
|  |- __init__.py
|
|- bar/
   |
   |- __init__.py
.

이제는 일반적으로 Defs 및 변수를 위해 작동하는 이렇게합니다.

import master

unknown_submodule = "foo"
if hasattr(master, unknown_submodule):
    pass # all's well
.

또는 똑같이 작동하는 attributeError를 잡습니다.

그러나 위의 파일 구조를 사용하면이 접근 방식을 가져올 수 없습니다. hasattr()는 항상 false (즉, 항상 attributeError가 던져집니다).

dir(master)를 보면이 출력이 나타납니다.

['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
.

__all__에서 master/__init__.py를 명시 적으로 지정하는 것은 도움이되지 않지만 dir ()을

변경합니다.
['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
.

어떤 아이디어, 내가 뭘 잘못하고 있는지, 또는 이러한 종류의 테스트를 달성 할 수있는 방법이있는 경우? (BTW : Python 2.6 Win / Cygwin, 그것이 중요한 경우)

도움이 되었습니까?

해결책

submodule은 명시 적으로 명시하지 않는 한 해당 부모 모듈의 속성이 아닙니다.단순히 모듈을 가져오고 ImportError를 catch하려고 시도하십시오.

try:
    __import__("os.peth", fromlist=[os])
except ImportError:
    pass
.

다른 팁

you can do

try:
 import module.submodule

except ImportError:
  print 'failed or whatever'

I recently had to check submodule existence and since I'm using python 3.4.1, I'm giving a new answer to the question:

In python 3.4.1 you can use importlib.util.find_spec(name, package=None) (https://docs.python.org/3.4/library/importlib.html#importlib.util.find_spec)

import importlib
module_exists = importlib.util.find_spec('path.to.my.module')

That easy =)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top