加载模块时python捕获NameError [英] python catching NameError when loading module
问题描述
我正在尝试捕获无法加载模块时发生的所有异常. 当前结果是未执行"except"块.
I'm trying to catch any exceptions that happen when you cannot load a module. The current results are that the "except" block does not get executed.
import sys
def loadModule(module):
try:
import module
except:
print """
Cannot load %s
For this script you will need:
cx_Oracle: http://cx-oracle.sourceforge.net/
pycrypto: https://www.dlitz.net/software/pycrypto/
paramiko: http://www.lag.net/paramiko/
""" % module
sys.exit(1)
loadModule(cx_Oracle)
错误:
Traceback (most recent call last):
File "./temp_script.py", line 16, in <module>
loadModule(cx_Oracle)
NameError: name 'cx_Oracle' is not defined
推荐答案
loadModule(cx_Oracle)
您认为您要将此功能传递给什么?到目前为止,代码中没有任何名为cx_Oracle
的东西.这就是为什么您收到NameError的原因.您甚至都没有进入该功能.
What do you think you are passing to this function? There is nothing named cx_Oracle
in the code so far. That's why you are getting a NameError. You aren't even getting into the function.
import module
您不能传递要导入的变量,它会将您输入的内容解释为模块的文字名称
You can't pass variables to import, it interprets what you put in as the literal name of the module
在这种情况下,我质疑您甚至需要一个功能.只需将try/except移到模块级别,然后直接导入cx_Oracle.
In this case, I question that you even need a function. Just move the try/except to the module level and import cx_Oracle directly.
仅因为我很好奇,这是一种使您可以创建可重用的异常捕获导入函数的方法.我不确定何时/如何使用它,但是这里是:
Just because I was curious, here is a way you can make a reusable exception-catching import function. I'm not sure when/how it would be useful, but here it is:
from contextlib import contextmanager
import sys
@contextmanager
def safe_import(name):
try:
yield
except:
print 'Failed to import ' + name
sys.exit(1)
with safe_import('cuckoo'):
import cuckoo
这篇关于加载模块时python捕获NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!