Skip to main content

Session Management

Session lifecycle, working directories, and logging configuration for Python applications

Overview

A script that runs unattended needs somewhere to work, a log of what it did, and a way to keep old runs from piling up. vcti-session gives each run a working directory, configures logging into it, and cleans up afterwards. SessionDir creates a uniquely named directory per run and prunes old ones by count and age; WorkDir uses a directory you name and leaves it alone. SessionHandler ties a SessionDir and a LogConfig into one context manager with hooks at each point of the lifecycle. Every setting resolves in the same order: constructor argument, then environment variable, then default.

Installation

pip install vcti-session

In requirements.txt

vcti-session>=1.1.0

In pyproject.toml dependencies

dependencies = [
    "vcti-session>=1.1.0",
]

Quick Start

A new directory for each run

from vcti.session import LogConfig, SessionDir, SessionHandler

session_dir = SessionDir(
    base_directory="sessions",
    max_session_dirs=10,
    max_age_days=7,
)
log_config = LogConfig(file_path="logs/app.log", level="info")

handler = SessionHandler(session_dir, log_config)
with handler.session_context() as session:
    # The working directory is now a new, uniquely named session directory,
    # and logging goes to <session>/logs/app.log.
    print(f"Working in: {session.path}")
# The log file is closed, the working directory restored, and sessions
# beyond the limits pruned.

A directory you choose

from vcti.session import LogConfig, WorkDir

work_dir = WorkDir(
    directory="my-work",
    log_config=LogConfig(file_path="app.log"),
    create_if_missing=True,
)
with work_dir.work_context():
    print(f"Working in: {work_dir.path}")

WorkDir never renames, prunes or deletes anything.

Configuration from the environment

from vcti.session import LogConfig, SessionDir

# Reads MYAPP_SESSION_DIR_PREFIX, MYAPP_SESSION_DIR_MAX_SESSION_DIRS, ...
session_dir = SessionDir(
    base_directory="sessions",
    env_prefix="MYAPP_",
    env_file=".env",  # loaded into the process environment first
)

# Reads MYAPP_SESSION_LOG_FILE_PATH, MYAPP_SESSION_LOG_LEVEL, ...
log_config = LogConfig(
    env_prefix="MYAPP_",
    default_file_path="logs/app.log",
    default_level="info",
)

A value passed to the constructor wins over the environment, which wins over the default_* argument.

Lifecycle hooks

from pathlib import Path

from vcti.session import SessionDir, SessionHandler


def on_created(path: Path) -> None:
    print(f"Session started: {path.name}")


def on_exit(path: Path, error: Exception | None) -> None:
    print(f"Session ended: {path.name}, error={error!r}")


def before_prune(dirs: list[Path]) -> None:
    print(f"About to delete {len(dirs)} old session(s)")


handler = SessionHandler(
    SessionDir(base_directory="sessions", max_session_dirs=1),
    on_session_created=on_created,
    on_session_exit=on_exit,
    on_before_prune=before_prune,
    on_session_error=lambda error: print(f"Session failed: {error}"),
)
with handler.session_context():
    pass

Key Classes

Class Purpose
SessionDir Creates uniquely named session directories and prunes old ones by count and age
WorkDir Context manager for a user-specified directory, with no naming or cleanup
SessionHandler Context manager combining a SessionDir and a LogConfig into a session lifecycle with hooks
LogConfig Logging settings: file path, level, console and color output, message format

Reference

Hooks

Hook Signature When
on_session_created (path: Path) -> None After the directory is created and logging is set up
on_session_error (error: Exception) -> None When an exception leaves the context
on_session_exit (path: Path, error: Exception | None) -> None When the context exits, before logging is closed
on_before_prune (dirs: list[Path]) -> None Before old sessions are deleted, when there are any

All hooks are optional. A hook that raises is logged as a warning and does not interrupt the session.

SessionDir settings

Argument Environment variable Default Description
prefix SESSION_DIR_PREFIX session_ Prefix of session directory names; must not be empty
timestamp_format SESSION_DIR_TIMESTAMP_FORMAT %Y-%m-%d-%H-%M-%S strftime format of the timestamp in the name
max_session_dirs SESSION_DIR_MAX_SESSION_DIRS 20 Session directories to keep (-1 = unlimited)
max_age_days SESSION_DIR_MAX_AGE_DAYS 10 Age in days after which a session is deleted (-1 = unlimited)

LogConfig settings

Argument Environment variable Default Description
file_path SESSION_LOG_FILE_PATH None Log file; a relative path is inside the session or work directory. None disables file logging
level SESSION_LOG_LEVEL info notset, trace, debug, verbose, info, warning, error or fatal
console_enabled SESSION_LOG_CONSOLE_ENABLED false Also log to the console
color_enabled SESSION_LOG_COLOR_ENABLED false ANSI colors in console output
message_format SESSION_LOG_MESSAGE_FORMAT (none) A preset name or a format string

With env_prefix="MYAPP_" the variables become MYAPP_SESSION_DIR_PREFIX, MYAPP_SESSION_LOG_LEVEL, and so on.

Working directory

SessionHandler and WorkDir change the process working directory inside the context and restore it on exit. Pass change_directory=False to leave it alone and use .path instead; a multi-threaded or async application should.


Dependencies


Documentation

If you want to… Read
Get started using the package Quick Start above
Choose a logging setup, run in threads, archive sessions before they are pruned docs/patterns.md
Understand the two directory strategies and the session lifecycle docs/design.md
Navigate and understand the source docs/source-guide.md

Metadata

Release files for vcti-session 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for vcti-session 1.1.0
File Size Uploaded Provenance Actions
vcti_session-1.1.0.tar.gz 33.6 kB With provenance Details for vcti_session-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for vcti-session 1.1.0
File Interpreter ABI Platform Actions
vcti_session-1.1.0-py3-none-any.whl Python 3 none any Details for vcti_session-1.1.0-py3-none-any.whl

Total release size: 50.9 kB

Release files / vcti_session-1.1.0.tar.gz

Download URL vcti_session-1.1.0.tar.gz
Size 33.6 kB
Tags Source
SHA-256 checksum
How to use checksums
25b93c976504591acdb3be53fcdd9a29266fbc720278eb06e4ca035ac67852fc
BLAKE2b-256 checksum
How to use checksums
3256b0f08549529b5e296115cd8adf238f81f5e0662a858c323b6d23aeaa4bdf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Release files / vcti_session-1.1.0-py3-none-any.whl

Download URL vcti_session-1.1.0-py3-none-any.whl
Size 17.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bb12c313d9ea1f78b4d75e9b1c85e16eae265bdd38a7cb8df83f09a8512ed064
BLAKE2b-256 checksum
How to use checksums
b9c2a50b80aa2d88ee63958c529e12d219a210f94b539afb5650e429afeb1e5d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Security for vcti-session 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for vcti_session-1.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page