[Tutor] How to get module name from ImportError

Steven D'Aprano steve at pearwood.info
Tue Nov 22 01:14:31 CET 2011


Nikunj.Badjatya at emc.com wrote:
> Hi All,
> 
> Please look at the following snippet.
> {{{
> 
> # User defined modules
> try:
>     from scripts import precheck
>     from scripts import validate
>     from scripts import constants
> except ImportError:
>     print("ERROR: One of the modules (..scripts/precheck.py, validate.py, constants) is not present.")
>     print("INFO : Please verify the above modules, and restart the installation")
>     sys.exit(1)
> 
> }}}
> 
> See the red line.

Please remember that 8% of men, and 1% of women, are colour blind and 
may not be able to distinguish red. In the computer community, that 
figure is probably higher: I have heard credible reports that red-green 
colour blindness is more common among mathematicians, scientists and 
computer programmers than normal.

Please also remember that many people, especially programmers, disable 
HTML in email, as it is a security and privacy risk. Consequently they 
will not see colours, fancy fonts, dancing paperclips, coloured 
backgrounds, or any other superfluous junk used in HTML email.



> I want to get the name of the particular module which is not available and hence causing ImportError.
> One of the ways can be to get the STDERR and process it using re. !?

Absolutely not. The error message is not part of the API of Python, 
which means it could change without warning.

It should be safe to assume that the error message itself will describe 
the missing module in some fashion, but parsing the error is the wrong 
solution.

The way I would do this is:

# Untested
try:
     from scripts import precheck, validate, constants
except ImportError as err:
     msg = err.args[0]
     msg += '\n whatever new message you want to add'
     err.args = (msg,)  # note the comma is important
     raise  # re-raise the exception


Hope that helps.



-- 
Steven



More information about the Tutor mailing list