でライブラリのクラスをインポートします。 PY:私はプロジェクト階層を以下しているのPython
from errors import SomeException
また、私はlibに/ some_script.py
from agent.errors import SomeException
にインポートするには、次のコードを使用します
問題は、私はlibに/エージェント/ some_agent_script.pyでSomeExceptionを上げたときに、その後のlib/some_script.pyがブロック以外でそれをキャッチすることはできませんです。
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)
私はモジュールをerros sys.modulesに見ることができます二回インポートされた:最初は「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')
このモジュールを2回インポートしないようにするにはどうすればよいですか?
Pythonのバージョンは何ですか? –
It's Python 2.6.6 – fey
関連する読者:[SO質問](http://stackoverflow.com/questions/1459236/module-reimported-if-imported-from-different-path)、[PEP 395](http: /www.python.org/dev/peps/pep-0395/) –