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>=2.0.0

In pyproject.toml dependencies

dependencies = [
    "vcti-session>=2.0.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: BaseException | 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; also usable as create_session() and close_session()
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; not for KeyboardInterrupt or SystemExit
on_session_exit (path: Path, error: BaseException | None) -> None When the context exits, before logging is closed; error is None only on a clean exit
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; not empty, no path separator or drive
timestamp_format SESSION_DIR_TIMESTAMP_FORMAT %Y-%m-%d-%H-%M-%S strftime format of the timestamp in the name; must not produce a path separator
max_session_dirs SESSION_DIR_MAX_SESSION_DIRS 20 Session directories to keep, -1 for unlimited
max_age_days SESSION_DIR_MAX_AGE_DAYS 10 Age in days after which a session is deleted, -1 for 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 and may not contain ..; an absolute path may be anywhere. 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.

Pruning and running sessions

A session directory is prunable when its name starts with the prefix and it is beyond max_session_dirs or older than max_age_days. The directory of a session that is still running inside a SessionHandler context is never pruned; it still counts toward max_session_dirs.

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 2.0.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 2.0.0
File Size Uploaded Provenance Actions
vcti_session-2.0.0.tar.gz 52.3 kB With provenance Details for vcti_session-2.0.0.tar.gz

Built distribution (wheel)

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

Total release size: 78.1 kB

Release files / vcti_session-2.0.0.tar.gz

Download URL vcti_session-2.0.0.tar.gz
Size 52.3 kB
Tags Source
SHA-256 checksum
How to use checksums
227501e0ea7683b1b6d7171f078449ed17714562ad2a4cfcf9fa9900bfdd67a2
BLAKE2b-256 checksum
How to use checksums
d45a71b52b6ccbf8e31094d8036edc52c034fb7dac0698e13950e30f55d05143
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-2.0.0-py3-none-any.whl

Download URL vcti_session-2.0.0-py3-none-any.whl
Size 25.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cba7f2860e949db9cddc513f10d22684c7fbf66049c65bbc7112609192119bba
BLAKE2b-256 checksum
How to use checksums
d4d8a00eec1cf95207a609d1eb64f9748bda21aee9c699cd3bfe623b1489bb70
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 2.0.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-2.0.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