gpt4 book ai didi

python - 尝试从多个位置导入模块的更简洁的方法?

转载 作者:太空狗 更新时间:2023-10-29 18:28:29 26 4
gpt4 key购买 nike

有没有办法整理下面的代码,而不是一系列嵌套的 try/except 语句?

try:
import simplejson as json
except ImportError:
try:
import json
except ImportError:
try:
from django.utils import simplejson as json
except:
raise "Requires either simplejson, Python 2.6 or django.utils!"

最佳答案

我在 http://mail.python.org/pipermail/python-list/2007-May/441896.html 找到了以下函数.它似乎工作得很好,而且我很确定它的导入方式不会影响您可能已经拥有的任何现有导入。

def module_exists(module_name):
try:
mod = __import__(module_name)
except ImportError:
return False
else:
return True

if module_exists('simplejson'):
import simplejson as json
elif module_exists('json'):
import json
elif module_exists('django.utils'):
from django.utils import simplejson as json
else:
raise ImportError('Requires either simplejson, Python 2.6 or django.utils')

我知道这看起来需要更多代码,但如果您经常这样做,该函数可以在其他地方重用。

关于python - 尝试从多个位置导入模块的更简洁的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/388173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com