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)
相关推荐
henrylin99992 分钟前
Quant Agent 完整系统规格
python·量化
三川6984 分钟前
Tkinter库的学习记录10-Message与Messagebox
python
吃饱了得干活4 分钟前
别只会传 temperature!一文挖透 LangChain 模型配置:Profile、全参数与运行时动态覆盖
python·langchain
shuoyuanAI11 分钟前
张家口专业的aigeo优化品牌找哪家
大数据·人工智能·python
卷无止境26 分钟前
《Deep Analysis with Polars》进阶分析技巧——深入解读
后端·python
大博士.J30 分钟前
视频号主体违规与认证上限?正确的解决方式
运维·python·自动化
Mr.朱鹏42 分钟前
【FastAPI 全栈实战 | 第2篇】Pydantic 数据校验与响应模型 —— 让 Bug 死在请求进来的那一刻
人工智能·python·fastapi
Xiangchu_1 小时前
安徽硅胶厂的转型困局:从家电到汽车,卡在哪
经验分享·python·阿里云·eclipse·汽车·制造
CTA终结者1 小时前
近期AI量化工具推荐,围绕最难推进的环节选择
人工智能·python
谙忆1 小时前
Python 常用图像处理库速查:Pillow、OpenCV、rembg、pillow-simd 各擅长什么、怎么选
图像处理·python·pillow