Python综合实战:从零开发一个命令行工具
目录Python综合实战从零开发一个命令行工具一、项目目标二、项目结构三、核心逻辑core.py四、命令行入口cli.py五、支持 python -m 运行六、打包安装pyproject.toml七、编写测试八、完整使用演示系列完结Python综合实战从零开发一个命令行工具本文是Python 入门教程系列的收官实战篇第 20 篇。前 19 篇学习了语法、库、工程化等知识本篇把它们串起来从零开发一个可发布的命令行工具。一、项目目标开发一个命令行工具fileman功能统计目录下文件数量与大小按扩展名分类整理文件支持命令行参数可安装到系统全局使用二、项目结构fileman/ ├── fileman/ │ ├── __init__.py │ ├── __main__.py # 支持 python -m fileman │ ├── cli.py # 命令行入口 │ └── core.py # 核心逻辑 ├── tests/ │ └── test_core.py ├── pyproject.toml ├── README.md └── .gitignore三、核心逻辑core.py# fileman/core.pyfrompathlibimportPathfromcollectionsimportCounterdefscan_directory(path):扫描目录返回文件统计信息rootPath(path)ifnotroot.exists():raiseFileNotFoundError(f目录不存在{path})files[fforfinroot.rglob(*)iff.is_file()]total_sizesum(f.stat().st_sizeforfinfiles)ext_counterCounter(f.suffix.lower()or(无扩展名)forfinfiles)return{total_files:len(files),total_size:total_size,top_extensions:ext_counter.most_common(5),}deforganize_files(source,target):按扩展名整理文件到子目录srcPath(source)dstPath(target)moved0forfileinsrc.iterdir():ifnotfile.is_file():continueextfile.suffix.lstrip(.).lower()orothertarget_dirdst/ext target_dir.mkdir(parentsTrue,exist_okTrue)new_pathtarget_dir/file.namefile.rename(new_path)moved1returnmoved四、命令行入口cli.py# fileman/cli.pyimportargparsefrom.coreimportscan_directory,organize_filesdefformat_size(size):格式化文件大小forunitin[B,KB,MB,GB]:ifsize1024:returnf{size:.1f}{unit}size/1024returnf{size:.1f}TBdefmain():parserargparse.ArgumentParser(progfileman,description文件管理命令行工具,)subparser.add_subparsers(destcommand)# scan 子命令p_scansub.add_parser(scan,help扫描目录统计)p_scan.add_argument(path,help要扫描的目录)# organize 子命令p_orgsub.add_parser(organize,help按类型整理文件)p_org.add_argument(source,help源目录)p_org.add_argument(-o,--output,defaultorganized,help目标目录)argsparser.parse_args()ifargs.commandscan:infoscan_directory(args.path)print(f文件总数{info[total_files]})print(f总大小{format_size(info[total_size])})print(扩展名统计)forext,countininfo[top_extensions]:print(f{ext}:{count}个)elifargs.commandorganize:movedorganize_files(args.source,args.output)print(f已整理{moved}个文件到{args.output}/ 目录)else:parser.print_help()if__name____main__:main()五、支持 python -m 运行# fileman/__main__.pyfrom.cliimportmainif__name____main__:main()六、打包安装pyproject.toml[build-system] requires [setuptools61.0] build-backend setuptools.build_meta [project] name fileman version 0.1.0 description 文件管理命令行工具 requires-python 3.8 [project.scripts] fileman fileman.cli:main# 安装到系统全局可用 fileman 命令pipinstall-e.# 直接使用fileman scan.fileman organize ~/Downloads七、编写测试# tests/test_core.pyimportpytestfromfileman.coreimportorganize_filesimporttempfilefrompathlibimportPathdeftest_organize_files():withtempfile.TemporaryDirectory()astmp:srcPath(tmp)/srcdstPath(tmp)/dstsrc.mkdir()(src/a.txt).write_text(hello)(src/b.jpg).write_bytes(b123)movedorganize_files(str(src),str(dst))assertmoved2assert(dst/txt/a.txt).exists()assert(dst/jpg/b.jpg).exists()运行pytest tests/ -v八、完整使用演示# 1. 扫描目录$ fileman scan ~/Downloads 文件总数125 总大小2.3GB 扩展名统计 .jpg:45个 .pdf:30个 .zip:20个 .docx:15个(无扩展名):15个# 2. 整理文件$ fileman organize ~/Downloads-o~/Organized 已整理125个文件到 ~/Organized/ 目录# 3. 效果$ls~/Organized jpg/ pdf/ zip/ docx/ other/系列完结至此Python 入门教程系列 20 篇全部完成阶段篇目入门1-4语法、OOP、文件、标准库进阶5-10网络、并发、数据库、数据分析、Web、调试深入11-14正则、异步、装饰器、测试工程15-16工程化、自动化办公扩展17-19机器学习、算法、Git实战20命令行工具全流程接下来的学习建议找真实项目练手把本系列技术用起来参与开源项目阅读优秀代码持续输出学习笔记巩固知识关注新技术方向AI、大数据、云原生感谢你一路读到这里祝你编程之路越走越远