[Tutor] How to get module name from ImportError

Dave Angel d at davea.name
Mon Nov 21 08:11:12 CET 2011


On 11/21/2011 01:23 AM, Nikunj.Badjatya at emc.com wrote:
> Exactly !
> Thanks a lot.
> 1)
You really shouldn't top-post.  Nor should you try to indicate something 
with color, since this is a text-based forum.

I would suggest that you do not try to parse error messages.  (If you're 
going to just print the message and exit, then there's no advantage in 
catching it.)  Instead, arrange the answer to be given to you directly.  
Two ways come to mind:

1) use separate try/catch blocks
2) use variables to indicate how far you got before the exception happened.

I think I would just start with

precheck = validate= constants = None

then after the exception is reported, you can check each of these with 
something like:

if constants:

One more thing.  You appear to be  using Python 3.  So the correct 
syntax for the except is:

      except ImportError as  error_obj:

Note that the value is *not* a string, but is an object of some subclass 
of ImportError.



> From: Christian Witts [mailto:cwitts at compuscan.co.za]
> Sent: Monday, November 21, 2011 11:36 AM
> To: Badjatya, Nikunj
> Cc: tutor at python.org
> Subject: Re: [Tutor] How to get module name from ImportError
>
> On 2011/11/21 07:54 AM, Nikunj.Badjatya at emc.com<mailto: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.
> 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. !?
>
> Is there a better alternate available .?
>
> Thanks
> Nikunj
>
>
>
>
> _______________________________________________
>
> Tutor maillist  -  Tutor at python.org<mailto:Tutor at python.org>
>
> To unsubscribe or change subscription options:
>
> http://mail.python.org/mailman/listinfo/tutor
>>>> try:
> ...     import nothing
> ... except ImportError, err_msg:
> ...     print err_msg
> ...
> No module named nothing
>
> Hope that helps.
> --
>
> Christian Witts
> Python Developer
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


-- 

DaveA



More information about the Tutor mailing list