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)
相关推荐
ASS-ASH3 分钟前
霸王色霸气的本质概括分析
人工智能·python·机器学习·大脑·脑电波
ValidationExpression9 分钟前
学习:词嵌入(Word Embedding / Text Embedding)技术
python·学习·ai
liliangcsdn20 分钟前
如何使用lambda对python列表进行排序
开发语言·python
葱明撅腚31 分钟前
seaborn绘图(下)
python·matplotlib·可视化·seaborn·图表绘制
半路_出家ren35 分钟前
3.python模拟勒索病毒
python·网络安全·密码学·网络攻击模型·base64·病毒·勒索病毒
jhf20201 小时前
2026汽车4S店GEO优化高性价比公司选型指南:从效果、成本到适配
python·汽车
叫我:松哥1 小时前
基于scrapy的网易云音乐数据采集与分析设计实现
python·信息可视化·数据分析·beautifulsoup·numpy·pandas
极智-9961 小时前
GitHub 热榜项目-日榜精选(2026-01-24)| AI智能体工具、Python生态等 | remotion、VibeVoice、goose等
人工智能·python·github·ai智能体·大模型部署·语音ai
YMLT花岗岩1 小时前
Python学习之-函数-入门训练-具有多个返回值的函数
python·学习
北鹤M1 小时前
用MeteoStat计算任意时刻经纬度真实气象数据
人工智能·python