5 Easy Ways To Check If Module Exists In Python Environment

Python scripts may run in different environments. Sometimes, you need specific features and modules that are only available in your custom environment, such as the python environment embedded in your software. How can you check if a module exists in the environment? How to disallow running your python script in the system’s standard python environment; How can you ensure that a custom python environment is active and provides all the required modules by the script?

Check If Module Exists By Importing The Module

Well, the straightforward answer is importing the specific module. If the module does not exist in the python environment, an exception may be raised (ModuleNotFoundError or ImportError based on your python version), and the script terminates.

Check If Module Exists – Import The Module at main.py
import blabla                         # ==> A1
print("The blabla module exists !!!") # ==> A2

If the blabla module does not exist, an exception will be raised. Since the exception is not handled, the python interrupter prints the exception’s traceback and terminates the script at A1.

Check If Module Exists – blabla module does not exist
$ python main.py
Traceback (most recent call last):                                                                                                                                                                                 File "/projects/s1/main.py", line 1, in <module>
  import blabla
    ModuleNotFoundError: No module named 'blabla' 

If the blabla module exist, the python interrupter will execute the print statement at A2

Check If Module Exists – blabla module exists
$ python main.py
The blabla module exists !!!

Check If Module Exists By Enclosing Import In Try-Except

The user can not run the script with the system’s standard python environment anymore. However, The ModuleNotFoundError or ImportError message and the displayed traceback might not be obvious to your users. They may find that the issue is a bug in your script. Therefore, You should provide a proper error message explaining the problem; that is, explain to the user that he can run this python script only in your custom environment as it requires specific modules.

To do this, Let’s enclose the import statement in a try-except construct and handle the ModuleNotFoundError or ImportError that will be raised when the module does not exist in the python environment.

Check If Module Exists – Enclosing import in try-except
import sys
try:
    import blabla
except ImportError or ModuleNotFoundError:
    # The blabla module does not exist, display proper error message and exit
    print('This script can only be run in blabla environment', file=sys.stderr)
    sys.exit(1)

Now, if the blabla module does not exist, a clear message error will be displayed, and the script will terminate.

Check If Module Exists – blabla module does not exist
$ python main.py
This script can only be run in blabla environment

Check If Module Exists With Function


While the above solution works, It may become tedious, especially if there are many such scripts or you need to check the availability of many modules. Of course, you can repeat the try/except for each module. You can add the check_enviroment function that tries to import all the specific modules:

Now, you can safely import the modules. If the user runs the script outside the custom environment, he will see a clear message that he can is not in the right environment.

Check If Module Exists With Function
def ensure_enviroment():
    try:
        import sys
        import math        
        import blabla1
        import blabla2
    except ModuleNotFoundError or ImportError as ee:
        print('This script can only be run in blabla environment : {0}'.format(ee.msg), file=sys.stderr)
        exit(1)

ensure_enviroment()

import sys
import math        
import blabla1
import blabla2

The first problem with this approach is the need to duplicate all the import statements inside the ensure_enviromnet function and write them in the main script after calling it. It can be tedious and error-prone. However, we must do it since imported modules in the ensure_enviromnet function are not available in the main script.

The second problem is apparent when you have several scripts you want to ensure your custom environment is active. In this case, you must duplicate this function in each script. Furthermore, some python linters may complain that we call a function before the import statements.

Check If Module Exists With Module

Let’s fix the second problem by writing the function in a separate module and importing this module before the import statements.

Check If Module Exists With Module – main.py
import ensure_environment

import math        
import blabla1
import blabla2

Check If Module Exists With Module – ensure_environment.py
import sys

def ensure_environment():
    try:
        import math        
        import blabla1
        import blabla2
    except ModuleNotFoundError or ImportError as ee:
        print('This script can only be run in blabla environment : {0}'.format(ee.msg), file=sys.stderr)
        exit(1)

ensure_environment()

We successfully fix the second problem,

However the first problem was not resolved. In the above solution, we duplicated all the import statements inside the ensure_enviromnet function of the ensure_enviromnet module and wrote them in the main script after importing it. As said, It can be tedious and error-prone. However, we must do it since the imported modules in the ensure_enviromnet are not available in the main script. Let’s Fix it.

Check If Module Exists With Exception Hook

The sys module provides a hook called sys.exceptionhook. Python interrupter calls this hook when an exception is raised. We can replace this hook with our customized function:

In this function, We will check if the exceptionType is ModuleNotFoundError or ImportError. If it is, we print a clear message to the user and terminates the script; otherwise, for other exceptions, we call the original hook.

Check If Module Exists With Module – main.py
import ensure_environment

import math        
import blabla1
import blabla2

Check If Module Exists With Module – ensure_environment.py
import sys

old_excepthook =  sys.excepthook
def ensure_enviroment_excepthook(exceptionType, exception, traceback):    
    if exceptionType == ModuleNotFoundError or exceptionType == ImportError:
        print('This script can only be run in blabla environment : {0}'.format(exception.msg), file=sys.stderr)
        exit(1)
    return old_excepthook(exceptionType , exception ,traceback)

sys.excepthook = ensure_enviroment_excepthook

How To Check If Custom Python Environment Is Active

We see five approaches to check whether the custom python environment is active. We see the problems of each approach and we find that the last approach (using the sys.excepthook) will display a proper and clear message to the user when the script runs outside the required custom environment with minimal effort. All you need to do is customize the ensure_enviroment_excepthook function to your needs and import the ensure_enviroment module before any other imports.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top