Code audit tool for python
—
Core functions for running pylama code analysis programmatically and via command line interface. These functions provide the primary entry points for both interactive command-line usage and programmatic integration.
Main console command entry point that parses arguments, loads configuration, and executes code checking.
def shell(args: List[str] = None, error: bool = True):
"""
Main console entry point for pylama command.
Args:
args: Command line arguments list. If None, uses sys.argv[1:]
error: Whether to exit with error code on finding issues
Returns:
List[Error]: List of errors found during checking
This function:
- Parses command line arguments and configuration files
- Sets up logging based on options
- Handles special modes (VCS hook installation, stdin input)
- Executes file checking and displays results
- Exits with appropriate code if error=True
"""Check multiple file paths with support for directory traversal and filtering.
def check_paths(
paths: Optional[List[str]],
options: Namespace,
code: str = None,
rootdir: Path = None,
) -> List[Error]:
"""
Check multiple file paths for code quality issues.
Args:
paths: List of file/directory paths to check. If None, uses options.paths
options: Parsed configuration options from parse_options()
code: Source code string for checking (used with single path)
rootdir: Root directory for relative path resolution
Returns:
List[Error]: All errors found across all checked files
This function:
- Expands directories to find Python files
- Filters files based on configuration
- Supports both synchronous and asynchronous processing
- Aggregates errors from all files
"""Core function for checking individual files with full linter integration.
def run(
path: str,
code: str = None,
rootdir: Path = CURDIR,
options: Namespace = None
) -> List[Error]:
"""
Run code checkers on a single file.
Args:
path: File path to check (relative to rootdir)
code: Source code string. If None, reads from file
rootdir: Root directory for path resolution
options: Configuration options. If None, uses defaults
Returns:
List[Error]: Errors found in the file
This function:
- Creates RunContext for the file
- Processes file-specific configuration and modelines
- Runs all configured linters on the file
- Collects and deduplicates errors
- Applies sorting based on configuration
"""Format and display errors using configured output format.
def display_errors(errors: List[Error], options: Namespace):
"""
Format and display errors using specified format.
Args:
errors: List of Error objects to display
options: Configuration options containing format settings
Supported formats:
- 'json': JSON array of error dictionaries
- 'pylint': Pylint-compatible format
- 'pycodestyle': pycodestyle-compatible format
- 'parsable': Default parsable format
- Custom format strings using error attributes
Output is sent to logger at WARNING level.
"""Deprecated function maintained for backward compatibility.
def check_path(
options: Namespace,
rootdir: str = None,
candidates: List[str] = None,
code: str = None,
) -> List[Error]:
"""
Legacy interface for checking files (deprecated).
This function is deprecated and will be removed in pylama 9.
Use check_paths() instead.
Args:
options: Configuration options
rootdir: Root directory path as string
candidates: List of file paths to check
code: Source code string
Returns:
List[Error]: Errors found during checking
"""from pylama.main import check_paths
from pylama.config import parse_options
# Check files with default configuration
options = parse_options([])
errors = check_paths(['mymodule.py', 'tests/'], options)
# Process results
if errors:
print(f"Found {len(errors)} issues:")
for error in errors:
print(f" {error.filename}:{error.lnum} - {error.message}")from pylama.main import check_paths
from pylama.config import parse_options
# Use specific linters and options
args = [
'--linters=pycodestyle,pyflakes,mccabe',
'--ignore=E501,W503',
'--max-line-length=100',
'src/'
]
options = parse_options(args)
errors = check_paths(None, options) # Uses paths from optionsfrom pylama.core import run
from pylama.config import parse_options
# Check code string directly
code = '''
def my_function():
unused_var = 42
print("Hello World")
'''
options = parse_options(['--linters=pyflakes'])
errors = run('example.py', code=code, options=options)
for error in errors:
print(f"Line {error.lnum}: {error.message}")import sys
from pylama.main import shell
# Run as if from command line
sys.argv = ['pylama', '--format=json', 'myproject/']
errors = shell(error=False) # Don't exit on errors
# Or with explicit arguments
errors = shell(['--linters=pylint', '--ignore=C0111', 'myfile.py'])DEFAULT_FORMAT: str = "{filename}:{lnum}:{col} [{etype}] {number} {message} [{source}]"
MESSAGE_FORMATS: Dict[str, str] = {
"pylint": "{filename}:{lnum}: [{etype}] {number} {message} [{source}]",
"pycodestyle": "{filename}:{lnum}:{col} {number} {message} [{source}]",
"parsable": DEFAULT_FORMAT,
}Install with Tessl CLI
npx tessl i tessl/pypi-pylama