I want to implement some friendlier error messages if the user tries to run a python script which tries to import modules that have not been installed. This includes printing out instructions on how to install the missing module.
One way to do this would be to put a try..catch block around the imports, but this is a bit ugly since it would turn something simple like
import some_module
into
try:
import some_module
except ImportError, e:
handle_error(e)
and it would have to be added to every file. Additionally, ImportError doesn't seem to store the name of the missing module anywhere (except for in the message) so you would have to put a separate try..catch around each import if you need to know the name (like I do). Parsing the name of the module is not the option since the message carried by ImportError might change for python version to version and depending on the user's locale.
I guess I could use sys.excepthook to catch all exceptions and pass those except ImportError along. Or would it be possible to define something like
safe_import some_module
that would behave like I want?
Does anyone know of any existing solutions to this problem?