Tuesday, July 30, 2013

Python - How to find the location of a module?

When a module is imported into a program, how to find out the path from where the module is getting picked?

    In the Unix world, when a command say ls is executed, the operating system searches in a list of directories for the command executable and once found, executes the command. The list of directories is maintained in the PATH variable.
    Similarly, in Python, whenever a module is imported, say "import collections', python also searches in a list of directories to find the module file "collections.py", and once found, includes the module. The list of directories to be searched is maintained in a list, sys.path, from the sys module. Hence, this can be accessed using the sys.path.

Let us write a script, findmod.py, to find the path of the module 'collections' :

import sys,os
from collections import Counter


for folder in sys.path:
    if os.path.isfile(fname):
       print fname
On running the above script, we get:
$ ./findmod.py
   sys.path contains the list of directories from where the modules is picked up. Since the collections module is present in one of these directories, the file is to be checked for existence in every directory. Once found, it is printed.

os.path.join -> This joins all the arguments given with the path separator( If Unix flavor, the path separator will be / , if Windows it will be \ ). The advantage of using join rather than normal string conatenation is portability. join will use the appropriate path separator depending on the operating system.

os.path.isfile -> This function checks whether a file exists or not.
Related Posts Plugin for WordPress, Blogger...

No comments:

Post a Comment