问题描述
这可能有一个明显的答案,但是我是一个初学者.我有一个模块"(实际上只是一个我经常使用的带有一堆功能的文件),在开始时我导入了许多其他模块.但是,由于我在许多系统上工作,因此并非所有模块都可以在任何特定计算机上加载.为了使事情变得更加困难,在导入软件包时,我还会更改软件包的名称-例如,matplotlib缩写为mp.
This probably has an obvious answer, but I'm a beginner. I've got a "module" (really just a file with a bunch of functions I often use) at the beginning of which I import a number of other modules. Because I work on many systems, however, not all modules may be able to load on any particular machine. To make things slightly more difficult, I also change the names of the packages when I import them -- for example, matplotlib gets abbreviated to mp.
我只想加载当前正在使用的系统上存在的那些模块,并对不使用的模块进行一些错误处理.我能想到的唯一方法是将每个import语句括在其自己的try块中,这似乎是非Python的.如果我将它们全部包含在同一个try块中,则无论哪个模块引发错误,都将阻止后续模块的加载.有什么想法会让事情看起来更漂亮吗?如果我不想更改他们的名字,那就太容易了...
What I'd like to do is only load those modules that exist on the system I'm currently using, and do some error handling on the ones that don't. The only way I can think of doing so is by enclosing each import statement inside its own try block, which seems pretty un-pythonic. If I enclose them all in the same try block, whichever module throws an error will prevent the subsequent modules from being loaded. Any ideas that might make things look prettier? It would be so easy if I didn't want to change their names...
推荐答案
我不认为try except
块是非Python语言的;相反,这是在Python上处理导入的一种常见方法.
I don't think try except
block is un-pythonic; instead it's a common way to handle import on Python.
引用深入Python :
下一个示例演示了如何 使用异常来支持 平台特定的功能.
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
这篇关于导入模块时的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!