Search This Blog

Showing posts with label Import. Show all posts
Showing posts with label Import. Show all posts

Sunday, March 16, 2014

ImportError handling

You run in to import errors by using the try...except blocks.
You run in to this error when the module that you are trying to import does not exist in the sys.path. However, if you want to gracefully continue your execution even if there is an import error (and if this what your program expects) then you can handle it using except.

try: import abcexcept ImportError: print("It is still OK to continue")

or

You can also chose to import sys path 

import search path

Python looks are several directories when you try to import a module. It mainly searched the directories defined in sys.path. This is a list and you can see it as follows:

>>> import sys
>>> sys.path
['', 'C:\\Python33\\Lib\\idlelib', 'C:\\Python33\\lib\\site-packages\\selenium-2.40.0-py3.3.egg', 'C:\\Windows\\system32\\python33.zip', 'C:\\Python33\\DLLs', 'C:\\Python33\\lib', 'C:\\Python33', 'C:\\Python33\\lib\\site-packages']

If you want it to see in other directories, you can make it search it by using the sys.path.insert( 0, new_path ). This is very useful, if you want to import your own custom module.