How To Import A Python Module From A Python File Full Path

When you develop python source code, you save custom modules in python source file. Each python file is a python module. And some times you need to import these python modules ( which you know full file path ) in other python source code at run time, this article will tell you how to implement it.

1. Load Python Module From Python File At Run Time.

1.1 For Python Version 3.

If your python version is 3, then you can use python importlib.util module’s spec_from_file_location, module_from_spec and loader.exec_module function to load and run a python module saved in a python source file.

Below example will load a custom python module that is saved in Test.py file.

# 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.

Python 2 use imp library, this library has been deprecated. Below source code will implement same function as above in 1.1. You can see the code is shorter than above.

# 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
READ :   How To Use Python ConfigParser To Read Write Configuration File

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.