import os
import logging
from logging.handlers import RotatingFileHandler
from functools import wraps
LOG_DIR ='LOGS'# Log directory
LOG_FILE ='app.log'# Log file name# Ensure the log directory exists
os.makedirs(LOG_DIR, exist_ok=True)# Create a custom log formatter
log_format ="%(asctime)s [%(levelname)s] - %(message)s"
formatter = logging.Formatter(log_format)# Create a rotating file handler with a max log file size of 10MB
log_handler = RotatingFileHandler(os.path.join(LOG_DIR, LOG_FILE), maxBytes=10*1024*1024, backupCount=5)
log_handler.setFormatter(formatter)# Create a logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(log_handler)# Define a decorator to log function callsdeflog_function_call(func):@wraps(func)defwrapper(*args,**kwargs):try:
logger.info(f"Calling function: {func.__name__}")
result = func(*args,**kwargs)
logger.info(f"Function {func.__name__} completed successfully")return result
except Exception as e:
logger.error(f"Function {func.__name__} failed with error: {str(e)}")raise e
return wrapper
# Usage example:@log_function_calldefexample_function():print("This is an example function.")if __name__ =="__main__":
example_function()
import argparse
import os
import sys
import logging
from LogHandle import log_function_call
# Define a class to handle command-line arguments and subcommandsclassCommandLineTool:def__init__(self):
self.parser = argparse.ArgumentParser(description="通用命令行工具")
self.subparsers = self.parser.add_subparsers(dest="command", title="命令列表")defadd_command(self, name, help_text, handler):
parser = self.subparsers.add_parser(name,help=help_text)
parser.set_defaults(handler=handler)@log_function_calldefrun(self):
args = self.parser.parse_args()ifhasattr(args,'handler'):
args.handler()if __name__ =="__main__":# Create the command-line tool
tool = CommandLineTool()# Add commands
tool.add_command("version","显示程序版本",lambda:print("版本号:1.0"))# Add more commands here# Run the command-line tool
tool.run()
文件操作 – File -Handler
import os
import logging
from pathlib import Path
from LogHandle import log_function_call
# Define a class to handle file operationsclassFileHandler:
FILE_SUFFIXES =['txt','csv','html','yaml']def__init__(self, file_path):
self.file_path = Path(file_path)
self.file_suffix = self.file_path.suffix[1:]# Remove the leading dot@log_function_calldefread_file(self):if self.file_suffix in self.FILE_SUFFIXES:# Add specific file reading logic based on the file typeif self.file_suffix =='txt':with self.file_path.open()asfile:returnfile.read()elif self.file_suffix =='csv':# Implement CSV file reading logicpasselif self.file_suffix =='html':# Implement HTML file reading logicpasselif self.file_suffix =='yaml':# Implement YAML file reading logicpasselse:raise ValueError("Unsupported file type")if __name__ =="__main__":# Example usage
file_handler = FileHandler("example.txt")try:
file_content = file_handler.read_file()print(file_content)except Exception as e:print(f"Error: {str(e)}")
数据操作 – DB-Handler
import os
import logging
from logging.handlers import RotatingFileHandler
from functools import wraps
import importlib
import sys
LOG_DIR ='LOGS'# Log directory
LOG_FILE ='app.log'# Log file name# Ensure the log directory exists
os.makedirs(LOG_DIR, exist_ok=True)# Create a custom log formatter
log_format ="%(asctime)s [%(levelname)s] - %(message)s"
formatter = logging.Formatter(log_format)# Create a rotating file handler with a max log file size of 10MB
log_handler = RotatingFileHandler(os.path.join(LOG_DIR, LOG_FILE), maxBytes=10*1024*1024, backupCount=5)
log_handler.setFormatter(formatter)# Create a logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(log_handler)# Define a decorator to log function callsdeflog_function_call(func):@wraps(func)defwrapper(*args,**kwargs):try:
logger.info(f"Calling function: {func.__name__}")
result = func(*args,**kwargs)
logger.info(f"Function {func.__name__} completed successfully")return result
except Exception as e:
logger.error(f"Function {func.__name__} failed with error: {str(e)}")raise e
return wrapper
# Define a class to handle database connections and operationsclassDatabaseHandler:
DB_SUFFIXES =['mysql','oracle','postgresql','redis','mongodb']def__init__(self, db_type, db_host, db_port, db_name, db_user, db_password):if db_type notin self.DB_SUFFIXES:raise ValueError("Unsupported database type")
self.db_type = db_type
self.db_module = importlib.import_module(db_type)
self.db_host = db_host
self.db_port = db_port
self.db_name = db_name
self.db_user = db_user
self.db_password = db_password
defconnect(self):try:# Create a database connection based on the database typeif self.db_type =='mysql':# Implement MySQL connection logicpasselif self.db_type =='oracle':# Implement Oracle connection logicpasselif self.db_type =='postgresql':# Implement PostgreSQL connection logicpasselif self.db_type =='redis':# Implement Redis connection logicpasselif self.db_type =='mongodb':# Implement MongoDB connection logicpassexcept Exception as e:raise e
defexecute_query(self, query):try:# Execute the provided query and return resultspassexcept Exception as e:raise e
definsert_record(self, table, data):try:# Insert a record into the specified tablepassexcept Exception as e:raise e
defupdate_record(self, table, data):try:# Update a record in the specified tablepassexcept Exception as e:raise e
defdelete_record(self, table, conditions):try:# Delete records from the specified table based on conditionspassexcept Exception as e:raise e
if __name__ =="__main__":# Example usage
db_handler = DatabaseHandler('mysql','localhost',3306,'mydb','root','password')try:
db_handler.connect()
results = db_handler.execute_query("SELECT * FROM mytable")print(results)except Exception as e:print(f"Error: {str(e)}")