py library
The 'py' library provides a collection of powerful, low-level utilities primarily focused on filesystem path manipulation, INI parsing, I/O, Python code introspection, and logging. Maintained by the pytest-dev team, it often serves as a foundational component for other testing and development tools. It is currently at version 1.11.0 and has a stable release cadence.
Warnings
- gotcha For new projects or general file system path manipulation, Python's built-in `pathlib` module (introduced in Python 3.4) is often the more idiomatic and recommended choice over `py.path`. `pathlib` provides a fully object-oriented interface for paths and is part of the standard library.
- gotcha The `py.log` module provides basic logging facilities. However, for robust application logging, structured logging, or integration with existing logging ecosystems, Python's standard `logging` module is generally more powerful and flexible, offering advanced features like handlers, formatters, and hierarchical loggers.
- gotcha The `py.code` module offers powerful introspection and manipulation of Python code objects, often utilized by testing frameworks like `pytest`. Directly relying on `py.code` for general-purpose introspection or metaprogramming in application code might lead to less standard or harder-to-maintain solutions. Python's `inspect` module or `ast` module typically provide more standard APIs for these tasks.
Install
-
pip install py
Imports
- path
import py.path; p = py.path.local('.') - code
import py.code; c = py.code.Source('print("hello")') - io
import py.io; cap = py.io.StdCapture()
- log
import py.log; py.log.setconsumer(my_consumer)
Quickstart
import py
import os
# Create a temporary local path object
temppath = py.path.local('my_temp_dir')
temppath.ensure(dir=True) # Ensure it's a directory
# Join paths and write content
filepath = temppath.join('hello.txt')
filepath.write('Hello, py world!')
# Read content
print(filepath.read())
# Cleanup
filepath.remove()
temppath.remove()