Adds variables to python traceback with simple, lightweight, controllable debugging capabilities.
Command-line tool for running Python scripts with enhanced traceback display. Provides a wrapper that executes Python scripts with automatic variable display in tracebacks, supporting all formatting options available in the library.
Run Python scripts with enhanced traceback output and configurable formatting options.
def run_script(
path: Path,
argv: List[str],
fmt: Format,
) -> int:
"""
Execute a Python script with enhanced traceback handling.
Sets up the execution environment with proper sys.path and sys.argv,
then executes the script with enhanced exception handling using
the printing_exc context manager.
Parameters:
- path: Path to the Python script to execute
- argv: Command-line arguments to pass to the script
- fmt: Format configuration for traceback display
Returns:
0 if script executed successfully, 1 if exception occurred
"""
def main() -> int:
"""
Main entry point for the command-line interface.
Parses command-line arguments, configures formatting options,
and executes the specified script with enhanced tracebacks.
Returns:
Exit code (0 for success, 1 for error)
"""Parse command-line arguments for script execution and formatting configuration.
def parse_args() -> Tuple[argparse.Namespace, Path, List[str]]:
"""
Parse command-line arguments for the CLI interface.
Supports all Format configuration options as command-line arguments
plus script path and script arguments.
Returns:
Tuple of (parsed_arguments, script_path, script_arguments)
"""
def parse_args_and_script_cmd(
raising_nohelp_noabbrev_parser: argparse.ArgumentParser,
) -> Tuple[argparse.Namespace, Path, List[str]]:
"""
Parse arguments and separate tool args from script command.
Parameters:
- raising_nohelp_noabbrev_parser: ArgumentParser with custom error handling
Returns:
Tuple of (parsed_arguments, script_path, script_arguments)
"""
def split_argv_to_own_and_script(
raising_noabbrev_parser: argparse.ArgumentParser,
argv: Optional[List[str]] = None,
) -> Tuple[List[str], List[str]]:
"""
Split command line arguments into tool args and script args.
Parameters:
- raising_noabbrev_parser: ArgumentParser instance
- argv: Arguments to parse (uses sys.argv if None)
Returns:
Tuple of (tool_arguments, script_arguments)
"""Custom exception handling for argument parsing.
class ParseError(RuntimeError):
"""Exception raised for argument parsing errors."""
pass
def raising_error_func(message: str) -> None:
"""
Error function that raises ParseError instead of calling sys.exit.
Parameters:
- message: Error message to include in exception
Raises:
ParseError with the provided message
"""# Run a Python script with enhanced tracebacks
traceback-with-variables my_script.py
# Run with command line arguments
traceback-with-variables my_script.py --input data.txt --output results.txt
# Run a module
traceback-with-variables -m my_module arg1 arg2# Custom value string length
traceback-with-variables --max-value-str-len 500 my_script.py
# Show context lines around errors
traceback-with-variables --before 2 --after 1 my_script.py
# Use specific color scheme
traceback-with-variables --color-scheme synthwave my_script.py
# Hide global variables
traceback-with-variables --no-globals my_script.py
# Multiple formatting options
traceback-with-variables \
--max-value-str-len 300 \
--color-scheme nice \
--before 1 \
--after 1 \
--objects-details 2 \
my_script.py input.dat# Only show frames from specific files
traceback-with-variables --skip-files-except ".*myproject.*" ".*main\.py" my_script.py
# Show brief output for certain files
traceback-with-variables --brief-files-except ".*third_party.*" my_script.pyfrom traceback_with_variables.main import run_script, parse_args, Format
from pathlib import Path
# Parse command line arguments
args, script_path, script_argv = parse_args()
# Create format from parsed arguments
fmt = Format.parse(args)
# Run the script
exit_code = run_script(
path=script_path,
argv=script_argv,
fmt=fmt
)
print(f"Script completed with exit code: {exit_code}")from traceback_with_variables.main import run_script
from traceback_with_variables import Format, ColorSchemes
from pathlib import Path
# Custom format for script execution
custom_fmt = Format(
max_value_str_len=400,
color_scheme=ColorSchemes.synthwave,
before=1,
after=1,
objects_details=2
)
# Run script with custom format
script_path = Path("debug_script.py")
script_args = ["--debug", "--input", "test_data.json"]
exit_code = run_script(
path=script_path,
argv=script_args,
fmt=custom_fmt
)
if exit_code == 0:
print("Script completed successfully")
else:
print("Script encountered an exception")import subprocess
import sys
from pathlib import Path
def run_with_enhanced_tracebacks(script_path: str, *args):
"""Run a Python script with enhanced tracebacks via CLI."""
cmd = [
sys.executable,
"-m", "traceback_with_variables",
"--color-scheme", "nice",
"--before", "1",
"--after", "1",
script_path
] + list(args)
result = subprocess.run(cmd, capture_output=True, text=True)
print("STDOUT:")
print(result.stdout)
print("\nSTDERR (with enhanced tracebacks):")
print(result.stderr)
return result.returncode
# Usage
exit_code = run_with_enhanced_tracebacks("test_script.py", "--verbose")import argparse
from traceback_with_variables import Format
# Create parser with Format arguments
parser = argparse.ArgumentParser(description="My application")
Format.add_arguments(parser)
# Add application-specific arguments
parser.add_argument("--input", help="Input file")
parser.add_argument("--output", help="Output file")
# Parse arguments
args = parser.parse_args()
# Create format from parsed args
fmt = Format.parse(args)
# Use format in application
print(f"Using format with max_value_str_len: {fmt.max_value_str_len}")
print(f"Color scheme: {fmt.color_scheme}")from traceback_with_variables.main import run_script
from traceback_with_variables import Format
from pathlib import Path
# The run_script function sets up the execution environment:
# - sys.path[0] = str(path.parent) # Script directory in path
# - sys.argv = [str(path)] + argv # Script args
# - Proper __name__ = '__main__' # Main module execution
# - Enhanced exception handling # Via printing_exc context
# Example of what happens internally:
script_path = Path("example.py")
script_args = ["arg1", "arg2"]
fmt = Format()
# This is equivalent to:
# cd /path/to/script/directory
# python example.py arg1 arg2
# but with enhanced tracebacks
exit_code = run_script(script_path, script_args, fmt)# Show help for all available options
traceback-with-variables --help
# Available options include:
# --max-value-str-len INT Maximum length for variable values (default: 1000)
# --ellipsis-rel-pos FLOAT Ellipsis position (default: 0.7)
# --max-exc-str-len INT Maximum exception string length (default: 10000)
# --objects-details INT Object inspection depth (default: 1)
# --ellipsis STRING Ellipsis string (default: ...)
# --before INT Context lines before error (default: 0)
# --after INT Context lines after error (default: 0)
# --color-scheme SCHEME Color scheme: auto, none, common, synthwave, nice
# --skip-files-except PATTERN File patterns to skip unless matching
# --brief-files-except PATTERN File patterns for brief output
# --no-globals Hide global variablesimport os
import sys
from traceback_with_variables.main import main
# Programmatically invoke the CLI
original_argv = sys.argv.copy()
try:
# Set up arguments for CLI
sys.argv = [
"traceback-with-variables",
"--color-scheme", "synthwave",
"--max-value-str-len", "300",
"--before", "1",
"target_script.py",
"--script-arg", "value"
]
# Run the CLI
exit_code = main()
print(f"CLI completed with exit code: {exit_code}")
finally:
# Restore original argv
sys.argv = original_argvInstall with Tessl CLI
npx tessl i tessl/pypi-traceback-with-variables