python catching NameError when loading module

旧时模样 提交于 2019-12-24 03:26:18

问题


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)

Error:

Traceback (most recent call last):
  File "./temp_script.py", line 16, in <module>
    loadModule(cx_Oracle)
NameError: name 'cx_Oracle' is not defined

回答1:


loadModule(cx_Oracle)

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

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



回答2:


The error is happening when Python is trying to look up the cx_Oracle variable before the loadModule function can even be called.

If you want to keep your current strategy, you probably really want to be using something like importlib.import_module so that you can import the module by name, like import_module('cx_Oracle').

I'd suggest doing something like this instead:

try:
    import cx_Oracle
except ImportError:
    print "Can't load the Oracle module"
    dosomething()

in the top level of your module. That's the Pythonic way of handling this situation.




回答3:


Always think about which exception you want to catch. Do not overgeneralize by just coding except:. In this case, you want to catch the ImportError. The argument you want to pass to your function loadModule should be of type string, e.g. loadModule('cx_Oracle') (then you will get rid of the NameError). For loading modules dynamically within loadModule have a look at for example Dynamic loading of python modules.



来源:https://stackoverflow.com/questions/12202121/python-catching-nameerror-when-loading-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!