Python
  • 01、基础篇
    • Python基础篇-001. Python简介
    • Python基础篇-002. Hello World
    • Python基础篇-003. 变量类型(一)
    • Python基础篇-004. 常量
    • Python基础篇-005. 运算符
    • Python基础篇-006. 条件语句
    • Python基础篇-007. 循环语句
    • Python基础篇-008. 变量类型(二)
    • Python基础篇-009. 函数(一)
    • Python基础篇-010. 函数(二)
    • Python基础篇-011. 变量作用域
    • Python基础篇-012. 自定义类(一)
    • Python基础篇-013. 自定义类(二)
    • Python基础篇-014. 模块
    • Python基础篇-015. 异常处理
  • 02、进阶篇
    • Python进阶篇-001. 文件IO
    • Python进阶篇-002. main.py
    • Python进阶篇-003. init.py
    • Python进阶篇-004. all
    • Python进阶篇-005. private
    • Python进阶篇-006. lambda表达式
    • Python进阶篇-007. 推导式
    • Python进阶篇-008. 迭代器
    • Python进阶篇-009. 生成器
    • Python进阶篇-010. 多线程
    • Python进阶篇-011. 数据处理基础函数(一)
    • Python进阶篇-012. 数据处理基础函数(二)
    • Python进阶篇-013. 包管理(一)
    • Python进阶篇-014. 包管理(二)
    • Python进阶篇-015. 包管理(三)
    • Python进阶篇-016. 包管理(四)
    • Python进阶篇-017. requirements.txt
    • Python进阶篇-018. venv
    • Python进阶篇-019. 头部注释
    • Python进阶篇-020. 优雅传参
    • Python进阶篇-021. 连接MySQL
  • 03、实践篇
    • Python实践篇-001. GitBook小工具(一)
    • Python实践篇-002. GitBook小工具(二)
Powered by GitBook
On this page
  • 一、创作声明
  • 二、需求提炼
  • 三、方案设计
  • 四、代码与解析
  • 五、写在最后
  1. 03、实践篇

Python实践篇-002. GitBook小工具(二)

[toc]

一、创作声明

实践篇将以需求为出发点来展开,不会涉及ChatGPT创作的内容。

二、需求提炼

三、方案设计

本期目标:完成第一个需求。方案上,我计划通过json配置文件的方式设置源目录和目标路径。

此外:

  1. 考虑到可扩展性,我还希望加入开关,来控制配置是否生效。

  2. 由于工作目录下存在一些临时文件,我希望排除掉,比如.DS_Store。

具体配置示例如下:

{
    "bookList": [
        {
            "sourceBookPath": "~/workplace/Java",
            "destBookPath": "~/workplace/GitBook/Java",
            "enabled": true
        },
        {
            "sourceBookPath": "~/workplace/Python",
            "destBookPath": "~/workplace/GitBook/Python",
            "enabled": false
        }
    ],
    "excludeFileList": [
        ".DS_Store"
    ]
}

具体执行方式我希望如下:

python gitBook.py

这里有两个关键点:

  1. 我不需要指定gitBook.py的绝对路径

  2. 配置文件从我当前路径下加载,也可以通过-c的方式指定

四、代码与解析

代码比较简单,语法都是前面讲到过的知识点,对各种模块的调用一般都是工作中边写边查,比如subprocess怎么用。

import os
import argparse
import json
import subprocess

DEFAULT_CONFIG_NAME = "config.json"
SUMMARY_FILE_NAME = "SUMMARY.md"
README_FILE_NAME = "README.md"


def parse_args():
    current_path = os.getcwd()
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config', type=str, default=os.path.join(current_path, DEFAULT_CONFIG_NAME),
                        required=False)
    args = parser.parse_args()
    config_file = args.config
    print("配置文件路径为:", config_file)
    return config_file


def load_file(file_name):
    with open(file_name, 'r') as file:
        file_data = json.load(file)
    return file_data


def write_file(file_name, file_content):
    with open(file_name, "w") as file:
        file.write(file_content)


def load_json_config(config_file):
    return load_file(config_file)


def gen_summary_content(root_book_path, file_path, prefix, is_root, exclude_files):
    for exclude_file in exclude_files:
        if os.path.basename(file_path) == exclude_file:
            return ""

    if os.path.isfile(file_path):
        content = "{} [{}]({})\n".format(prefix, os.path.splitext(os.path.basename(file_path))[0],
                                         os.path.join(os.path.basename(root_book_path),
                                                      os.path.relpath(file_path, root_book_path)))
        return content
    if os.path.isdir(file_path):
        content = "{} [{}]({})\n".format(prefix, os.path.splitext(os.path.basename(file_path))[0],
                                         README_FILE_NAME)
        prefix_prefix = "    "
        if is_root:
            content = ""
            prefix_prefix = ""
        for file in sorted(os.listdir(file_path)):
            content = content + gen_summary_content(root_book_path, os.path.join(file_path, file),
                                                    prefix_prefix + prefix, False, exclude_files)
        return content


class Book:
    def __init__(self, source_book_path, dest_book_path, enabled, exclude_files):
        self.source_book_path = source_book_path
        self.dest_book_path = dest_book_path
        self.enabled = enabled
        self.exclude_files = exclude_files

    def gen_summary_content(self):
        return gen_summary_content(self.source_book_path, self.source_book_path, "*", True, self.exclude_files)

    def compile(self):
        if self.enabled is False: return
        shell_command = "cp -r {} {}".format(self.source_book_path, self.dest_book_path)
        print(shell_command)
        subprocess.run(shell_command, shell=True, capture_output=False, text=True)
        summary_content = self.gen_summary_content()
        write_file(os.path.join(self.dest_book_path, SUMMARY_FILE_NAME), summary_content)
        print(summary_content)


def compile_book_list(book_list):
    for book in book_list:
        book.compile()


def parse_file_json_data(file_json_data):
    raw_book_list = file_json_data['bookList']
    book_list = []
    for item in raw_book_list:
        book = Book(item['sourceBookPath'], item['destBookPath'], item['enabled'], file_json_data['excludeFileList'])
        book_list.append(book)
    return book_list


if __name__ == '__main__':
    # 解析命令行参数
    config_file = parse_args()
    # 加载配置文件
    file_json_data = load_json_config(config_file)
    # 将配置文件的内容转化为对象
    book_list = parse_file_json_data(file_json_data)
    # 对每个对象执行编译
    compile_book_list(book_list)

五、写在最后

更多技术分享,点击传送门:https://github.com/maxiaolu66/profile

PreviousPython实践篇-001. GitBook小工具(一)

Last updated 1 year ago