<p>使用logger时,您必须实现错误的日志记录。<br/>
在Python中,默认情况下,错误只记录到控制台。<br/>
所以,如果您想使用logger,就必须添加逻辑来捕获和记录错误。在</p>
<p><code>try except</code>块是在Python上处理导入的常用方法。在</p>
<p>引用<a href="http://diveintopython.net/file_handling/index.html" rel="nofollow noreferrer">Dive into Python</a>:</p>
<blockquote>
<p>There are a lot of other uses for
exceptions besides handling actual
error conditions. <strong>A common use in the
standard Python library is to try to
import a module, and then check
whether it worked</strong>. 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).</p>
<p>The next example demonstrates how to
use an exception to support
platform-specific functionality. </p>
</blockquote>
<pre><code>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
</code></pre>