A tool for converting between pip-style and pipfile requirements.
—
RequirementsLib provides comprehensive exception classes for handling various error conditions during requirement parsing, file operations, and format conversions. These exceptions enable proper error handling and debugging in applications using the library.
Core exception classes that serve as the foundation for more specific error types.
class RequirementError(Exception):
"""
Base exception for requirement-related errors.
Raised when parsing or processing requirements fails due to
malformed input, invalid specifications, or processing errors.
"""Handle missing or invalid parameters during requirement processing.
class MissingParameter(Exception):
"""
Raised when required parameters are missing.
Provides methods for generating and displaying helpful error messages
to assist with debugging parameter-related issues.
"""
def __init__(self, param):
"""
Initialize with missing parameter name.
Parameters:
- param: Name of the missing parameter
"""
@classmethod
def get_message(cls, param):
"""
Generate error message for missing parameter.
Parameters:
- param: Parameter name
Returns:
str: Formatted error message
"""
def show(self, param):
"""
Display error message to stderr.
Parameters:
- param: Parameter name
"""Handle various types of file corruption and parsing errors.
class FileCorruptException(OSError):
"""
Base exception for corrupt file errors.
Extends OSError to provide file-specific error handling with
support for backup file paths and detailed error messages.
"""
def __init__(self, path, *args, backup_path=None):
"""
Initialize with file path and optional backup path.
Parameters:
- path: Path to the corrupt file
- backup_path: Optional path to backup file
"""
def get_message(self, path, backup_path=None):
"""
Generate error message for file corruption.
Parameters:
- path: Path to corrupt file
- backup_path: Optional backup file path
Returns:
str: Formatted error message
"""
def show(self):
"""Display error message to user."""Handle errors specific to Pipfile.lock operations.
class LockfileCorruptException(FileCorruptException):
"""
Raised when lockfile is corrupt or unreadable.
Occurs when Pipfile.lock files have invalid JSON, missing required
sections, or other structural problems that prevent parsing.
"""
def __init__(self, path, backup_path=None):
"""
Initialize with lockfile path.
Parameters:
- path: Path to corrupt lockfile
- backup_path: Optional backup file path
"""
def get_message(self, path, backup_path=None):
"""
Generate lockfile-specific error message.
Parameters:
- path: Path to corrupt lockfile
- backup_path: Optional backup file path
Returns:
str: Formatted error message
"""
def show(self, path, backup_path=None):
"""
Display lockfile error message.
Parameters:
- path: Path to corrupt lockfile
- backup_path: Optional backup file path
"""Handle errors specific to Pipfile operations.
class PipfileCorruptException(FileCorruptException):
"""
Raised when Pipfile is corrupt or unreadable.
Occurs when Pipfile has invalid TOML syntax, missing required
sections, or other structural problems that prevent parsing.
"""
def __init__(self, path, backup_path=None):
"""
Initialize with Pipfile path.
Parameters:
- path: Path to corrupt Pipfile
- backup_path: Optional backup file path
"""
def get_message(self, path, backup_path=None):
"""
Generate Pipfile-specific error message.
Parameters:
- path: Path to corrupt Pipfile
- backup_path: Optional backup file path
Returns:
str: Formatted error message
"""
def show(self, path, backup_path=None):
"""
Display Pipfile error message.
Parameters:
- path: Path to corrupt Pipfile
- backup_path: Optional backup file path
"""Handle missing file errors.
class PipfileNotFound(FileNotFoundError):
"""
Raised when Pipfile cannot be found.
Extends FileNotFoundError to provide Pipfile-specific context
when attempting to load Pipfiles that don't exist.
"""
def __init__(self, path, *args, **kwargs):
"""
Initialize with Pipfile path.
Parameters:
- path: Path to missing Pipfile
"""from requirementslib import Requirement, Pipfile, Lockfile
from requirementslib.exceptions import (
RequirementError,
MissingParameter,
LockfileCorruptException,
PipfileCorruptException,
PipfileNotFound
)
# Handle requirement parsing errors
try:
req = Requirement.from_line("invalid requirement line")
except RequirementError as e:
print(f"Failed to parse requirement: {e}")
# Handle missing parameter errors
try:
# Some operation that might have missing parameters
pass
except MissingParameter as e:
print(f"Missing required parameter: {e}")
e.show(e.args[0]) # Show detailed error messagefrom requirementslib import Pipfile, Lockfile
from requirementslib.exceptions import (
PipfileNotFound,
PipfileCorruptException,
LockfileCorruptException
)
# Handle Pipfile loading errors
try:
pipfile = Pipfile.load("./Pipfile")
except PipfileNotFound as e:
print(f"Pipfile not found: {e}")
# Create new Pipfile or use defaults
pipfile = Pipfile.load("./Pipfile", create=True)
except PipfileCorruptException as e:
print(f"Pipfile is corrupt: {e}")
e.show(e.args[0]) # Show detailed error message
# Handle lockfile loading errors
try:
lockfile = Lockfile.load("./Pipfile.lock")
except LockfileCorruptException as e:
print(f"Lockfile is corrupt: {e}")
e.show(e.args[0], e.args[1] if len(e.args) > 1 else None)
# Regenerate lockfile from Pipfile
lockfile = Lockfile.lockfile_from_pipfile("./Pipfile")from requirementslib import Requirement, Pipfile, Lockfile
from requirementslib.exceptions import *
import sys
def safe_parse_requirement(line):
"""Safely parse a requirement line with error handling."""
try:
return Requirement.from_line(line)
except RequirementError as e:
print(f"Error parsing requirement '{line}': {e}", file=sys.stderr)
return None
except MissingParameter as e:
print(f"Missing parameter while parsing '{line}':", file=sys.stderr)
e.show(e.args[0])
return None
def safe_load_pipfile(path):
"""Safely load a Pipfile with comprehensive error handling."""
try:
return Pipfile.load(path)
except PipfileNotFound:
print(f"Pipfile not found at {path}, creating new one")
return Pipfile.load(path, create=True)
except PipfileCorruptException as e:
print(f"Pipfile at {path} is corrupt:")
e.show(path)
return None
except Exception as e:
print(f"Unexpected error loading Pipfile: {e}", file=sys.stderr)
return None
def safe_load_lockfile(path, pipfile_path=None):
"""Safely load a lockfile with fallback to regeneration."""
try:
return Lockfile.load(path)
except LockfileCorruptException as e:
print(f"Lockfile at {path} is corrupt:")
e.show(path)
if pipfile_path:
print("Attempting to regenerate from Pipfile...")
try:
return Lockfile.lockfile_from_pipfile(pipfile_path)
except Exception as regen_error:
print(f"Failed to regenerate lockfile: {regen_error}")
return None
except Exception as e:
print(f"Unexpected error loading lockfile: {e}", file=sys.stderr)
return None
# Example usage
requirements_lines = [
"requests>=2.25.0",
"invalid_requirement_line",
"django[redis]==3.2.0"
]
for line in requirements_lines:
req = safe_parse_requirement(line)
if req:
print(f"Successfully parsed: {req.name} {req.specifiers}")
pipfile = safe_load_pipfile("./Pipfile")
if pipfile:
lockfile = safe_load_lockfile("./Pipfile.lock", "./Pipfile")from requirementslib.exceptions import RequirementError
import logging
# Set up logging for better error tracking
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def process_requirements_with_logging(requirements_lines):
"""Process requirements with detailed logging."""
successful = []
failed = []
for line in requirements_lines:
try:
req = Requirement.from_line(line)
successful.append(req)
logger.info(f"Successfully parsed: {req.name}")
except RequirementError as e:
failed.append((line, str(e)))
logger.error(f"Failed to parse '{line}': {e}")
except Exception as e:
failed.append((line, f"Unexpected error: {str(e)}"))
logger.error(f"Unexpected error parsing '{line}': {e}")
logger.info(f"Processed {len(successful)} requirements successfully")
logger.info(f"Failed to process {len(failed)} requirements")
return successful, failedInstall with Tessl CLI
npx tessl i tessl/pypi-requirementslib