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
What do you think you are passing to this function? There is nothing named
cx_Oraclein the code so far. That’s why you are getting a NameError. You aren’t even getting into the function.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: