当前位置: 代码网 > it编程>前端脚本>Python > 基于Python从零开发一个命令行工具的完整代码

基于Python从零开发一个命令行工具的完整代码

2026年08月26日 Python 我要评论
一、项目目标开发一个命令行工具 fileman,功能:统计目录下文件数量与大小按扩展名分类整理文件支持命令行参数可安装到系统全局使用二、项目结构fileman/├── fileman/│ ├──

一、项目目标

开发一个命令行工具 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.py
from pathlib import path
from collections import counter

def scan_directory(path):
    """扫描目录,返回文件统计信息"""
    root = path(path)
    if not root.exists():
        raise filenotfounderror(f"目录不存在:{path}")

    files = [f for f in root.rglob("*") if f.is_file()]
    total_size = sum(f.stat().st_size for f in files)
    ext_counter = counter(f.suffix.lower() or "(无扩展名)" for f in files)

    return {
        "total_files": len(files),
        "total_size": total_size,
        "top_extensions": ext_counter.most_common(5),
    }

def organize_files(source, target):
    """按扩展名整理文件到子目录"""
    src = path(source)
    dst = path(target)
    moved = 0

    for file in src.iterdir():
        if not file.is_file():
            continue
        ext = file.suffix.lstrip(".").lower() or "other"
        target_dir = dst / ext
        target_dir.mkdir(parents=true, exist_ok=true)
        new_path = target_dir / file.name
        file.rename(new_path)
        moved += 1

    return moved

四、命令行入口(cli.py)

# fileman/cli.py
import argparse
from .core import scan_directory, organize_files

def format_size(size):
    """格式化文件大小"""
    for unit in ["b", "kb", "mb", "gb"]:
        if size < 1024:
            return f"{size:.1f}{unit}"
        size /= 1024
    return f"{size:.1f}tb"

def main():
    parser = argparse.argumentparser(
        prog="fileman",
        description="文件管理命令行工具",
)
    sub = parser.add_subparsers(dest="command")

    # scan 子命令
    p_scan = sub.add_parser("scan", help="扫描目录统计")
    p_scan.add_argument("path", help="要扫描的目录")

    # organize 子命令
    p_org = sub.add_parser("organize", help="按类型整理文件")
    p_org.add_argument("source", help="源目录")
    p_org.add_argument("-o", "--output", default="organized", help="目标目录")

    args = parser.parse_args()

    if args.command == "scan":
        info = scan_directory(args.path)
        print(f"文件总数:{info["total_files"]}")
        print(f"总大小:{format_size(info["total_size"])}")
        print("扩展名统计:")
        for ext, count in info["top_extensions"]:
            print(f"  {ext}: {count} 个")
    elif args.command == "organize":
        moved = organize_files(args.source, args.output)
        print(f"已整理 {moved} 个文件到 {args.output}/ 目录")
    else:
        parser.print_help()

if __name__ == "__main__":
    main()

五、支持 python -m 运行

# fileman/__main__.py
from .cli import main

if __name__ == "__main__":
    main()

六、打包安装(pyproject.toml)

[build-system]
requires = ["setuptools>=61.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 命令)
pip install -e .

# 直接使用
fileman scan .
fileman organize ~/downloads

七、编写测试

# tests/test_core.py
import pytest
from fileman.core import organize_files
import tempfile
from pathlib import path

def test_organize_files():
    with tempfile.temporarydirectory() as tmp:
        src = path(tmp) / "src"
        dst = path(tmp) / "dst"
        src.mkdir()
        (src / "a.txt").write_text("hello")
        (src / "b.jpg").write_bytes(b"123")

        moved = organize_files(str(src), str(dst))
        assert moved == 2
        assert (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从零开发一个命令行工具的完整代码的文章就介绍到这了,更多相关python开发命令行工具内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com