Want some programming help? [close]

Get Module File Information in Python

Overview

Introduction

In Python sometimes you need to figure out where a function lives on the hard disk, or what file is calling your function. The os module provides tools for getting file and directory information and the inspect module provides the ability to inspect the stack and see what module is calling your function.

Get file information about a module

The os module in Python provides many useful ways for getting the file name of where a module lives. There are functions to get file names, directory names, and get absolute paths. Check out this example:

# Example assumes this file is named test.py
# and lives in /home/nanodano/
# https://docs.python.org/3/library/os.path.html

import os

# Prints the full path of where the os.py module resides
print(os.__file__)


# The name of file where this print statement is written
print(__file__)
# test.py

# Get the full absolute path using os.path.abspath()
print(os.path.abspath(__file__))
# /home/nanodano/test.py

# Get the directory name of a file with os.path.dirname()
print(os.path.dirname(__file__))
# Relative to current directory
# Prints an empty string if being run from current directory
# Prints .. if being called from a deeper directory

# Combine to get absolute path of the directory containing the python file
print(os.path.abspath(os.path.dirname(__file__)))
# /home/nanodano

## Other functions that might be useful
# os.path.join()  # Join directory names using system specific dir separator
# os.sep()  # Path separator character (system specific)
# os.getcwd()  # Full absolute path
# os.walk()  # Generator to walk dirs recursively
# os.listdir()  # Current dir or specific dir

Get module and file name of caller

In some cases, your function is getting called by code from other .py files. If you want to figure out where your function is being called from, you can inspect the stack. The inspect module provides a way to get this data.

import inspect

# Import this to other module and call it
def print_caller_info():
    # Get the full stack
    stack = inspect.stack()
   
    # Get one level up from current
    previous_stack_frame = stack[1]
    print(previous_stack_frame.filename)  # Filename where caller lives

    # Get the module object of the caller
    calling_module = inspect.getmodule(stack_frame[0])
    print(calling_module)
    print(calling_module.__file__)


if __name__ == '__main__':
    print_caller_info()

Conclusion

After reading this, you should know how to get the relative and absolute filename of the current Python modules as well as modules that are calling your function.

Reference links

Advertisement