我有两个"api兼容"的软件包fast
和slow
;彼此之间。如果fast
可用,我想从它导入,否则从slow
导入。我当前的工作解决方案是
import imp
try:
imp.find_module('fast')
from fast.UtilityFunctions import UtilityFunctions
from fast.Utilities.Log import Log
from fast.model.device_driver import DriverModel
...
except ImportError:
from slow.UtilityFuntions import UtilityFunctions
...
# normal code
有更好的写法吗?我可以消除上面的复制粘贴工作吗?也就是说,这个伪代码的python等价是什么?
import imp
try:
imp.find_module('fast')
alias found=fast
except ImportError
alias found=slow
from found.UtilityFuntions import UtilityFunctions
...
为什么不直接导入这些模块呢?
try:
import fast as found
except ImportError:
import slow as found
from found.UtilityFuntions import UtilityFunctions
try:
import some_specific_module as module
except ImportError:
import other_module
试试这段代码!