Get the path of a particular module source using sys.path

For this method, we will be using the sys module. The sys.path variable of sys module contains all the directories which will be searched for modules at runtime. So by knowing these directories we can manually check where our particular module exists. To implement this we have to write the following in python shell:-

Python




# importing sys module
import sys
 
# importing sys.path
print(sys.path)


This will return the list of all directories which will be searched for the module at runtime.

Output:

[‘/home’, ‘/usr/lib/python2.7’, ‘/usr/lib/python2.7/plat-x86_64-linux-gnu’, ‘/usr/lib/python2.7/lib-tk’, 

‘/usr/lib/python2.7/lib-old’, ‘/usr/lib/python2.7/lib-dynload’, ‘/usr/local/lib/python2.7/dist-packages’, 

‘/usr/lib/python2.7/dist-packages’]

How to locate a particular module in Python?

In this article, we will see how to locate a particular module in Python. Locating a module means finding the directory from which the module is imported. When we import a module the Python interpreter searches for the module in the following manner:

  • First, it searches for the module in the current directory.
  • If the module isn’t found in the current directory, Python then searches each directory in the shell variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list of directories.
  • If that also fails python checks the installation-dependent list of directories configured at the time Python is installed.

The sys.path contains the list of the current directory, PYTHONPATH, and the installation-dependent default. We will discuss how to use this and other methods to locate the module in this article. 

Similar Reads

Get the location of a particular module in Python using the OS module

For a pure Python module, we can locate its source by module_name.__file__. This will return the location where the module’s .py file exists. To get the directory we can use os.path.dirname() method in OS module. For example, if we want to know the location of the ‘random’ module using this method we will type the following in the python file....

Get the path of a particular module source using sys.path

...

Get the location of a particular module source using help(module_name)

For this method, we will be using the sys module. The sys.path variable of sys module contains all the directories which will be searched for modules at runtime. So by knowing these directories we can manually check where our particular module exists. To implement this we have to write the following in python shell:-...

Contact Us