gpt4 book ai didi

python - 导入模块时的错误处理

转载 作者:IT老高 更新时间:2023-10-28 22:03:10 26 4
gpt4 key购买 nike

这可能有一个明显的答案,但我是初学者。我有一个“模块”(实际上只是一个包含我经常使用的一堆函数的文件),在它的开头我导入了许多其他模块。然而,因为我在许多系统上工作,并不是所有的模块都可以在任何特定的机器上加载。为了让事情变得更加困难,我还在导入包时更改了包的名称——例如,matplotlib 缩写为 mp。

我想做的只是加载那些存在于我当前使用的系统上的模块,并对那些不存在的模块进行一些错误处理。我能想到的唯一方法是将每个 import 语句包含在它自己的 try block 中,这似乎很不符合 Python 风格。如果我将它们全部包含在同一个 try block 中,则无论哪个模块抛出错误都会阻止后续模块被加载。有什么想法可以让事情看起来更漂亮吗?如果我不想改变他们的名字,那就太容易了……

最佳答案

我不认为 try except block 是非 Python 的;相反,这是在 Python 上处理导入的常用方法。

引用 Dive into Python :

There are a lot of other uses for exceptions besides handling actual error conditions. A common use in the standard Python library is to try to import a module, and then check whether it worked. Importing a module that does not exist will raise an ImportError exception. You can use this to define multiple levels of functionality based on which modules are available at run-time, or to support multiple platforms (where platform-specific code is separated into different modules).

The next example demonstrates how to use an exception to support platform-specific functionality.

try:
import termios, TERMIOS
except ImportError:
try:
import msvcrt
except ImportError:
try:
from EasyDialogs import AskPassword
except ImportError:
getpass = default_getpass
else:
getpass = AskPassword
else:
getpass = win_getpass
else:
getpass = unix_getpass

关于python - 导入模块时的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3131217/

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