#!/usr/bin/env python3 import re import sys filepath = sys.argv[1] # Read the file with open(filepath, 'r') as f: lines = f.readlines() # Find the line with 'logger = logging.getLogger(__name__)' has_logger = any('logger = logging.getLogger(__name__)' in line for line in lines) has_logging_import = any('import logging' in line for line in lines) if not has_logging_import: # Find where to insert import for i, line in enumerate(lines): if line.startswith('import ') or line.startswith('from '): lines.insert(i, 'import logging\n') break if not has_logger: # Find where to insert logger (after imports) for i, line in enumerate(lines): if line.startswith('class ') or line.startswith('def '): lines.insert(i, '\n') lines.insert(i + 1, 'logger = logging.getLogger(__name__)\n') break # Replace print statements new_lines = [] for line in lines: # Replace print(f"...) with logger.debug(f"...") if 'print(f"' in line and not line.strip().startswith('#'): line = line.replace('print(f"', 'logger.debug(f"') elif 'print(f\'' in line and not line.strip().startswith('#'): line = line.replace('print(f\'', 'logger.debug(f\'') new_lines.append(line) # Write back with open(filepath, 'w') as f: f.writelines(new_lines) print(f'Done! Fixed logging in {filepath}')