Get a Python module's location

vegaseat 3 Tallied Votes 682 Views Share

A simple way to find out a Python module's location on your drive.

''' module_origin1.py
Where does a given module come from?
You could use module.__path__
but not all modules have a .pth file
tested with Python27 and Python33  by  vegaseat  22oct2013
'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk
import os

print(os.path.dirname(tk.__file__))

''' 
result (Python27) ...
c:\python27\lib\lib-tk
result (Python33) ...
c:\python33\lib\tkinter
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Getting the needed information can be as simple as ...

import pip
print(pip)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can also get the location from help(module) under FILE ...

import collections
help(collections)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Get more detail this way ...

''' inspect101.py
explore Python module inspect
'''

import inspect
import glob

# check if there is a file glob.py
try:
    print(inspect.getsourcefile(glob))
except TypeError:
    print("source file not found")

print('-'*60)

# retrieve the source code of glob.py
try:
    print(inspect.getsource(glob))
except IOError:
    print("source code not found")

print('-'*60)

# check if an object is built in or give file location
import json
object = json
try:
    file_path = inspect.getfile(object)
    print(file_path)
    if "__init__.py" in file_path:
        print("This is a package")
except TypeError:
    print("{} is a built-in module, class, or function".format(object))

print('-'*60)

# check if an object is built in or give file location
object = str
try:
    file_path = inspect.getfile(object)
    print(file_path)
    if "__init__.py" in file_path:
        print("This is a package")
except TypeError:
    print("{} is a built-in module, class, or function".format(object))

# where is the function getmodule() of module inspect located
print('-'*60)
print(inspect.getmodule(inspect.getmodule))
Gribouillis 1,391 Programming Explorer Team Colleague
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.