Finding out what REALLY went wrong when an `ImportError` is raised

Take Django for example in manage.py:

try:
    import settings
except ImportError:
    sys.stderr.write("Error: Can't find the file 'settings.py'...")

It seems legal, but what happens when it settingsimports non_existant_lib_foo?

Well, you were sent to chase the geese for all the possible things that you could do with help PATH, etc.

Of course, you can use except ImportError as e:and simply print the actual error message, but what if you want to catch only a specific error and give really good advice, for example above?

You no longer want to use regexp or, at best, assume that the "right" module could not import and then display the message.

Is there a better way to handle this?

+3
3

, - , , . ImportError " , , , ", .

" ", . imp.find_module .

+5

, , , , , :

try:
    import settings
except ImportError as exc:
    sys.stderr.write("Error: failed to import settings module ({})".format(exc))

, (, - , sys.path ), settings.

, , , ( ) debug() info().

, if 'settings' not in str(exc): raise imp.find_module(), .

0

One thing that I found very frustrating is that when you catch the import error, you really go down the deep rabbit hole right away.

Take a hint.

Make no mistake importing traps. An example is manage.pynot a good practice.

Do not do that.

import errors should be very, very rare.

-1
source

Source: https://habr.com/ru/post/1794315/


All Articles