Path Handling Demo

This example demonstrates how to use the cross-platform path utilities provided by libp2p.utils.paths.

After installing py-libp2p (pip install -e . from a checkout, or pip install libp2p), you can run the demo as a console script or as a module:

$ python -m pip install libp2p
Collecting libp2p
...
Successfully installed libp2p-x.x.x
$ path-handling

From a source checkout you can also run:

$ python -m examples.path_handling.path_handling_demo

The full source code for the implementation is below:

 1"""
 2Robust Example: Cross-platform path handling with libp2p.utils.paths
 3
 4This script demonstrates production-ready best practices for file and directory
 5operations using py-libp2p path utilities. These utilities ensure your code works on
 6Windows, macOS, and Linux.
 7"""
 8
 9import logging
10from pathlib import Path
11
12from libp2p.utils.paths import (
13    create_temp_file,
14    ensure_dir_exists,
15    get_script_dir,
16    get_temp_dir,
17    join_paths,
18    resolve_relative_path,
19)
20
21
22def setup_logging(level: int = logging.INFO) -> None:
23    """Configure logging for the example."""
24    logging.basicConfig(
25        level=level,
26        format="%(asctime)s %(levelname)s %(message)s",
27    )
28
29
30def write_and_read_temp_file(temp_file: Path) -> None:
31    """Write to and read from a temporary file, with error handling."""
32    try:
33        with temp_file.open("w", encoding="utf-8") as f:
34            f.write("py-libp2p path utilities demo\n")
35        logging.info(f"Wrote to temp file: {temp_file}")
36        with temp_file.open("r", encoding="utf-8") as f:
37            content = f.read()
38        logging.info(f"Read from temp file: {content.strip()}")
39    except Exception as e:
40        logging.error(f"Error handling temp file: {e}")
41
42
43def main() -> None:
44    """Run robust path handling demo."""
45    setup_logging()
46
47    # Join paths in a cross-platform way
48    data_dir: Path = join_paths(get_temp_dir(), "py-libp2p-demo", "data")
49    try:
50        ensure_dir_exists(data_dir)
51        logging.info(f"Data directory ensured: {data_dir}")
52    except Exception as e:
53        logging.error(f"Failed to create data directory: {e}")
54        return
55
56    # Get the directory of this script
57    try:
58        script_dir: Path = get_script_dir(__file__)
59        logging.info(f"Script directory: {script_dir}")
60    except Exception as e:
61        logging.error(f"Could not determine script directory: {e}")
62        return
63
64    # Create a temporary file and demonstrate file I/O
65    temp_file: Path | None = None
66    try:
67        temp_file = create_temp_file(prefix="demo_")
68        logging.info(f"Created temp file: {temp_file}")
69        write_and_read_temp_file(temp_file)
70    except Exception as e:
71        logging.error(f"Failed to create or use temp file: {e}")
72
73    # Resolve a relative path from the script directory (repo root README)
74    try:
75        rel_path: Path = resolve_relative_path(script_dir, "../../README.md")
76        if rel_path.exists():
77            logging.info(f"Resolved README.md path: {rel_path}")
78        else:
79            logging.warning(f"README.md not found at resolved path: {rel_path}")
80    except Exception as e:
81        logging.error(f"Failed to resolve relative path: {e}")
82
83    # Clean up temp file (optional, safe for production)
84    if temp_file:
85        try:
86            temp_file.unlink(missing_ok=True)
87            logging.info(f"Cleaned up temp file: {temp_file}")
88        except Exception as e:
89            logging.warning(f"Could not remove temp file: {e}")
90
91
92if __name__ == "__main__":
93    main()

API reference (Sphinx)

Submodules

examples.path_handling.path_handling module

Robust Example: Cross-platform path handling with libp2p.utils.paths

This script demonstrates production-ready best practices for file and directory operations using py-libp2p path utilities. These utilities ensure your code works on Windows, macOS, and Linux.

examples.path_handling.path_handling.main() None

Run robust path handling demo.

examples.path_handling.path_handling.setup_logging(level: int = 20) None

Configure logging for the example.

examples.path_handling.path_handling.write_and_read_temp_file(temp_file: Path) None

Write to and read from a temporary file, with error handling.

examples.path_handling.path_handling_demo module

Entry point for the path handling demo.

This allows running the example as a CLI tool via python -m examples.path_handling.path_handling_demo or as a console script (path-handling) if registered in pyproject.toml.

Package contents