Python脚本运行日志案例1

目的:
每次运行脚本时都会在源目录下生成一个详细的处理日志文件,记录了所有关键信息,同时保持控制台的简洁输出。

案例要求:

  1. 输入信息模块化:将目录输入检查模块化
  2. 优化路径处理,去除不必要的引号处理
  3. 修改日志记录方式,在process_files函数中记录关键信息并保存到源目录
import os
import shutil
import re
from pathlib import Path
import datetime

def get_directory_input(prompt, create_if_not_exists=False):
    """获取目录输入,提供统一的验证逻辑"""
    while True:
        path = input(prompt).strip()
        # 移除用户可能复制路径时带有的引号
        path = path.strip('"\'')
        
        if not path:
            print("错误: 路径不能为空!")
            continue
            
        path_obj = Path(path)
        
        if not path_obj.exists():
            if create_if_not_exists:
                create = input(f"目录 '{path}' 不存在,是否创建? (y/n): ").strip().lower()
                if create in ['y', 'yes']:
                    try:
                        path_obj.mkdir(parents=True, exist_ok=True)
                        print(f"已创建目录: {path}")
                        return path
                    except Exception as e:
                        print(f"创建目录失败: {e}")
                else:
                    print("操作已取消")
                    exit()
            else:
                print(f"错误: 路径 '{path}' 不存在!")
                continue
        elif not path_obj.is_dir():
            print(f"错误: '{path}' 不是目录!")
            continue
            
        return path

def get_user_input():
    """获取用户输入的三个关键参数,提供更友好的交互体验"""
    print("=" * 50)
    print("数据文件处理工具")
    print("=" * 50)
    
    # 获取源目录
    source_dir = get_directory_input("请输入源目录路径 (SOURCE_DIR): ")
    
    # 获取目标目录
    target_dir = get_directory_input("请输入目标目录路径 (TARGET_DIR): ", create_if_not_exists=True)
    
    # 获取日期
    while True:
        date_str = input("请输入日期 (格式: YYYYMMDD, 例如 20241231): ").strip()
        if not re.match(r"^\d{8}$", date_str):
            print("错误: 日期格式不正确!")
            continue
        break
    
    # 确认输入
    print("\n" + "=" * 50)
    print("\n请确认您的输入:")
    print(f"源目录: {source_dir}")
    print(f"目标目录: {target_dir}")
    print(f"日期: {date_str}")
    print("=" * 50)
    confirm = input("\n是否确认以上信息? (y/n): ").strip().lower()
    if confirm not in ['y', 'yes']:
        print("操作已取消")
        exit()
    
    return source_dir, target_dir, date_str

def process_files(source_dir, target_dir, date_str):
    """处理文件的主要逻辑"""
    source_path = Path(source_dir)
    target_path = Path(target_dir)
    
    # 准备日志内容
    log_content = []
    log_content.append("=" * 50)
    log_content.append("文件处理日志")
    log_content.append(f"生成时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    log_content.append("=" * 50)
    log_content.append(f"源目录: {source_dir}")
    log_content.append(f"目标目录: {target_dir}")
    log_content.append(f"日期: {date_str}")
    log_content.append("=" * 50)
    
    # 获取文件列表
    file_list = list(source_path.glob("*.txt"))
    planned_count = len(file_list)
    log_content.append(f"计划处理文件数量: {planned_count}")
    
    # 处理文件
    actual_count = 0
    error_messages = []
    
    for file_path in file_list:
        try:
            # 构建新文件名(添加日期前缀)
            new_filename = f"{date_str}_{file_path.name}"
            dest_path = target_path / new_filename
            
            # 复制文件
            shutil.copy2(file_path, dest_path)
            print(f"已处理: {file_path.name} -> {new_filename}")
            actual_count += 1
        except Exception as e:
            error_msg = f"处理文件 {file_path.name} 时出错: {e}"
            print(error_msg)
            error_messages.append(error_msg)
    
    # 记录处理结果
    log_content.append(f"实际处理文件数量: {actual_count}")
    
    if error_messages:
        log_content.append("=" * 50)
        log_content.append("错误信息:")
        for error in error_messages:
            log_content.append(error)
    
    log_content.append("=" * 50)
    log_content.append("处理完成!")
    log_content.append("=" * 50)
    
    # 保存日志到源目录
    log_filename = f"processing_log_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
    log_path = source_path / log_filename
    
    try:
        with open(log_path, 'w', encoding='utf-8') as log_file:
            log_file.write("\n".join(log_content))
        print(f"\n处理日志已保存到: {log_path}")
    except Exception as e:
        print(f"保存日志文件失败: {e}")
    
    return actual_count

def main():
    """主函数"""
    try:
        # 获取用户输入
        SOURCE_DIR, TARGET_DIR, DATE = get_user_input()
        
        # 执行文件处理
        print("\n开始处理文件...")
        count = process_files(SOURCE_DIR, TARGET_DIR, DATE)
        
        print("\n" + "=" * 50)
        print(f"处理完成! 实际共处理 {count} 个文件。")
        print("=" * 50)
        
    except KeyboardInterrupt:
        print("\n\n操作被用户中断")
    except Exception as e:
        print(f"\n程序执行出错: {e}")

# 使用示例
if __name__ == "__main__":
    main()

解释:

  1. 创建了 get_directory_input() 函数来模块化目录输入验证逻辑
  2. 简化了路径处理,只移除用户可能复制路径时带有的引号
  3. 简化日志记录方式:
    • process_files() 函数中收集所有需要记录的信息
    • 记录输入参数、计划处理文件数量、实际处理文件数量和错误信息
    • 将日志保存为文本文件到源目录
    • 日志文件名包含时间戳以避免覆盖
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值