jaraco.context

6.1.2 · active · verified Sat Mar 28

jaraco.context is a Python library providing useful decorators and context managers for common programming patterns. It offers tools like `ExceptionTrap` for exception handling, `pushd` for temporary directory changes, `tarball` for extracting archives, and `temp_dir` for managing temporary file system resources. The current version is 6.1.2, and it maintains an active release schedule with several updates in the past year.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the `temp_dir` context manager to create and automatically clean up a temporary directory, and the `pushd` context manager to temporarily change and restore the current working directory.

import os
from jaraco.context import temp_dir, pushd

with temp_dir() as tmp_dir_path:
    print(f"Temporary directory created at: {tmp_dir_path}")
    assert os.path.isdir(tmp_dir_path)

    # The temporary directory is automatically removed here
    assert not os.path.exists(tmp_dir_path)

# Example with pushd
current_cwd = os.getcwd()
with temp_dir() as tmp_path_for_pushd:
    with pushd(tmp_path_for_pushd):
        print(f"Current working directory changed to: {os.getcwd()}")
        assert os.getcwd() == os.fspath(tmp_path_for_pushd)
    print(f"Current working directory restored to: {os.getcwd()}")
    assert os.getcwd() == current_cwd

view raw JSON →