When creating Python source code, you often save custom modules in separate Python files. Each of these files serves as a Python module. Occasionally, you may find the need to import these modules (whose full file paths you’re aware of) into other Python source code during runtime. This article outlines how to accomplish this.
1. Load Python Module From Python File At Run Time.
1.1 For Python Version 3.
If you’re working with Python version 3, you have the option to utilize the `importlib.util` module. This module offers functions such as `spec_from_file_location`, `module_from_spec`, and `loader.exec_module`, which allow you to load and execute a Python module saved within a Python source file.
The following example demonstrates how to load a custom Python module saved in a file named “Test.py“:
# first import importlib.util module. >>> import importlib.util >>> # get python module spec from the provided python source file. The spec_from_file_location function takes two parameters, the first parameter is the module name, then second parameter is the module file full path. >>> test_spec = importlib.util.spec_from_file_location("Test", "/home/.../Test.py") >>> # pass above test_spec object to module_from_spec function to get custom python module from above module spec. >>> test_module = importlib.util.module_from_spec(test_spec) >>> # load the module with the spec. >>> test_spec.loader.exec_module(test_module) >>> # invoke the module variable. >>> test_module.user_name 'jerry' >>> # create an instance of a class in the module. >>> test_hello = test_module.TestHello() >>> # call the module class's function. >>> test_hello.print_hello_message() hello jerry
Below is the source code of Test.py.
user_name = 'jerry' class TestHello: def print_hello_message(self): print('hello ' + user_name)
1.2 For Python Version 2.
In Python 2, the `imp` library was commonly used for similar functionalities, though it has been deprecated. Below is a condensed implementation achieving the same functionality as described earlier:
# import imp library. >>> import imp # use imp library's load_source function to load the custom python module from python source file. The second parameter is the python module file full path. >>> test_module = imp.load_source('Test', '/home/.../Test.py') # invoke the module variable. >>> test_module.user_name 'jerry' >>> # create an instance of a class defined in the module. >>> test_hello = test_module.TestHello() >>> # call the module class function. >>> test_hello.print_hello_message() hello jerry