python 库 类_在Python中导入库类

我有以下项目层次结构:

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')

我该怎么做才能让这个模块不要导入两次?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值