Initial commit by AGI Operating System
This commit is contained in:
179
hello_world.py
Normal file
179
hello_world.py
Normal file
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Enhanced Hello World Script
|
||||
Version: 1.0.1
|
||||
Author: The Optimizer - Performance & Security Engineer
|
||||
Date: 2026-03-16
|
||||
Description: Enhanced hello world script with comprehensive logging,
|
||||
error handling, and CLI support.
|
||||
Optimized for security and performance.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import sys
|
||||
from logging.handlers import RotatingFileHandler
|
||||
import traceback
|
||||
|
||||
# Global configuration
|
||||
LOG_FILE = "hello_world.log"
|
||||
LOG_MAX_BYTES = 5 * 1024 * 1024 # 5MB
|
||||
LOG_BACKUP_COUNT = 3
|
||||
DEFAULT_NAME = "World"
|
||||
|
||||
|
||||
def setup_logging():
|
||||
"""Configure comprehensive logging system"""
|
||||
try:
|
||||
logger = logging.getLogger()
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
file_handler = RotatingFileHandler(
|
||||
LOG_FILE,
|
||||
maxBytes=LOG_MAX_BYTES,
|
||||
backupCount=LOG_BACKUP_COUNT,
|
||||
encoding="utf-8",
|
||||
)
|
||||
file_handler.setLevel(logging.DEBUG)
|
||||
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(logging.INFO)
|
||||
|
||||
formatter = logging.Formatter(
|
||||
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
)
|
||||
|
||||
file_handler.setFormatter(formatter)
|
||||
console_handler.setFormatter(formatter)
|
||||
|
||||
logger.addHandler(file_handler)
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
logging.info("Logging system initialized successfully")
|
||||
return logger
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to initialize logging system: {e}")
|
||||
logging.debug(traceback.format_exc())
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def parse_arguments():
|
||||
"""Parse command-line arguments with comprehensive validation"""
|
||||
try:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Enhanced Hello World Script with comprehensive features",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-n",
|
||||
"--name",
|
||||
type=str,
|
||||
default=DEFAULT_NAME,
|
||||
help="Name to greet (default: World)",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--log-level",
|
||||
type=str.upper,
|
||||
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
|
||||
default="INFO",
|
||||
help="Set logging level (default: INFO)",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-v",
|
||||
"--version",
|
||||
action="version",
|
||||
version="Enhanced Hello World Script 1.0.1",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.log_level:
|
||||
logging.getLogger().setLevel(getattr(logging, args.log_level))
|
||||
|
||||
logging.info(f"Command-line arguments parsed successfully: {args}")
|
||||
return args
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to parse command-line arguments: {e}")
|
||||
logging.debug(traceback.format_exc())
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def greet(name):
|
||||
"""Generate greeting message with validation"""
|
||||
try:
|
||||
if not name or not isinstance(name, str):
|
||||
raise ValueError("Name must be a non-empty string")
|
||||
|
||||
if len(name) > 100:
|
||||
raise ValueError("Name cannot exceed 100 characters")
|
||||
|
||||
message = f"Hello, {name}!"
|
||||
logging.info(f"Generated greeting message: {message}")
|
||||
return message
|
||||
|
||||
except ValueError as e:
|
||||
logging.error(f"Validation error in greet function: {e}")
|
||||
raise
|
||||
except Exception as e:
|
||||
logging.error(f"Unexpected error in greet function: {e}")
|
||||
logging.debug(traceback.format_exc())
|
||||
raise
|
||||
|
||||
|
||||
def main():
|
||||
"""Main application entry point with comprehensive error handling"""
|
||||
try:
|
||||
logging.info("Application started")
|
||||
|
||||
logger = setup_logging()
|
||||
|
||||
args = parse_arguments()
|
||||
|
||||
try:
|
||||
message = greet(args.name)
|
||||
print(message)
|
||||
logging.info("Greeting displayed successfully")
|
||||
|
||||
except ValueError as e:
|
||||
logging.error(f"Invalid input: {e}")
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
except Exception as e:
|
||||
logging.critical(f"Unexpected error during greeting: {e}")
|
||||
logging.debug(traceback.format_exc())
|
||||
print(
|
||||
"An unexpected error occurred. Check logs for details.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
logging.info("Application completed successfully")
|
||||
|
||||
except SystemExit as e:
|
||||
logging.warning(f"Application exiting with code: {e.code}")
|
||||
raise
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.warning("Application interrupted by user")
|
||||
print("\nOperation cancelled by user.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
except Exception as e:
|
||||
logging.critical(f"Fatal error in main application: {e}")
|
||||
logging.debug(traceback.format_exc())
|
||||
print(
|
||||
"A fatal error occurred. Check logs for details.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user