我有以下项目层次结构:
project_dir
lib
__init__.py
...
some_script.py
...
agent
__init__.py
...
errors.py
some_agent_script.py
...
lib / agent / erros.py中有SomeException类定义
我使用以下代码在lib / agent / some_agent_script.py中导入它们:
from errors import SomeException
我还使用以下代码在lib / some_script.py中导入
from agent.errors import SomeException
问题是当我在lib / agent / some_agent_script.py中引发SomeException时,lib / some_script.py无法在except块中捕获它:
try:
# Here comes a call to lib/agent/some_agent_script.py function
# that raises SomeException
except SomeException, exc:
# Never goes here
print(exc)
except Exception, exc:
print(exc.__class__.__name__) # prints "SomeException"
# Let's print id's
print(id(exc.__class__))
print(id(SomeException))
# They are different!
# Let's print modules list
pprint.pprint(sys.modules)
我可以在sys.modules中看到erros模块被导入了两次:第一个是’agent.errors’键,第二个是’lib.agent.errors’键
以下代码是正确的,但它不是一个漂亮的解决方案:
agent_errors = sys.modules.get('agent.errors')
from agent_errors import SomeException
try:
# Here comes a call to lib/agent/some_agent_script.py function
except SomeException:
print('OK')
我该怎么做才能让这个模块不要导入两次?