python日志输出和命令行参数解析示例

代码包含日志终端输出、日志文件输出和命令行参数解析示例

主要功能,根据命令行参数复制对应比例的文件到指定的文件夹中,并输出相应日志

python 复制代码
import os
import random
import shutil
import logging
import argparse
def copy_random_files(input_folder, output_folder, percentage=10):
    # 获取输入文件夹中的所有文件
    all_files = os.listdir(input_folder)
    
    # 计算需要复制的文件数量
    num_files_to_copy = int(len(all_files) * percentage / 100)
    
    # 随机选择要复制的文件
    files_to_copy = random.sample(all_files, num_files_to_copy)
    if os.path.isdir(output_folder):
    #删除输出文件夹内容
        shutil.rmtree(output_folder)
    # 确保输出文件夹存在,如果不存在则创建
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    
    # 复制文件到输出文件夹
    for file_name in files_to_copy:
        input_path = os.path.join(input_folder, file_name)
        output_path = os.path.join(output_folder, file_name)

        shutil.copy(input_path, output_path)
        logging.info(f"Copying {input_path} to {output_path}")

def setup_logging(log_file, log_level):
    logging.basicConfig(filename=log_file, level=log_level, format='%(asctime)s - %(levelname)s - %(message)s')
    console_handler = logging.StreamHandler()
    console_handler.setLevel(log_level)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    console_handler.setFormatter(formatter)
    logging.getLogger('').addHandler(console_handler)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Copy a random percentage of files from one folder to another.')
    parser.add_argument('-i', '--input', default='img_npz_3008', help='Input folder path')
    parser.add_argument('-o', '--output', default='img_calibrate', help='Output folder path')
    parser.add_argument('-p', '--percentage', type=int, default=10, help='Percentage of files to copy (default: 10)')
    parser.add_argument('-lf', '--log-file', default='copy_random_files.log', help='Log file path (default: copy_random_files.log)')
    parser.add_argument('-ll','--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], default='INFO', help='Log level (default: INFO)')
    args = parser.parse_args()

    setup_logging(args.log_file, getattr(logging, args.log_level))
    logging.info(f"Copying {args.percentage}% of files from {args.input} to {args.output}")


    
    copy_random_files(args.input, args.output , args.percentage)
相关推荐
星云穿梭12 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵12 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠18 小时前
大模型之LangGraph技术体系
python·llm
hboot1 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780511 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780512 天前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠2 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3102 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫2 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔2 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试