#!/usr/bin/env python3 """Script to replace print statements with logging in Python files.""" import re import sys def replace_prints_in_file(filepath): """Replace print statements with logger calls in a file.""" with open(filepath, 'r') as f: content = f.read() original_content = content # Add logger import if not present if 'logger = logging.getLogger(__name__)' not in content and 'import logging' in content: # Already has logging import but no logger setup pass elif 'import logging' not in content: # Need to add logging import lines = content.split('\n') import_idx = 0 for i, line in enumerate(lines): if line.startswith('import ') or line.startswith('from '): import_idx = i + 1 lines.insert(import_idx, 'import logging') lines.insert(import_idx + 1, '') lines.insert(import_idx + 2, 'logger = logging.getLogger(__name__)') content = '\n'.join(lines) # Replace simple print statements with logger.debug # Pattern: print(f"...") content = re.sub( r'^(\s*)print\(f"([^"]+)"\)', r'\1logger.debug(f"\2")', content, flags=re.MULTILINE ) # Pattern: print(f'...') content = re.sub( r"^(\s*)print\(f'([^']+)'\)", r'\1logger.debug(f"\2")', content, flags=re.MULTILINE ) # Pattern: print("...") content = re.sub( r'^(\s*)print\("([^"]+)"\)', r'\1logger.debug("\2")', content, flags=re.MULTILINE ) # Pattern: print(f"...", end="") content = re.sub( r'^(\s*)print\(f"([^"]+)",\s*end="[^"]*"\)', r'\1logger.debug(f"\2")', content, flags=re.MULTILINE ) # Pattern: print(f"..." \n f"...") - multiline content = re.sub( r'print\(f"([^"]+)"\s*\n\s*f"', r'logger.debug(f"\1" \n f"', content ) with open(filepath, 'w') as f: f.write(content) # Count changes changes = content.count('logger.debug') - original_content.count('logger.debug') if changes > 0: print(f"Replaced ~{changes} print statements in {filepath}") return changes if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python replace_prints.py ") sys.exit(1) filepath = sys.argv[1] replace_prints_in_file(filepath)