最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已未解决】用Python从gitbook的markdown文件SUMMARY.md生成相关md文件

Python crifan 3750浏览 0评论
对于:
之前遇到VSCode的bug:
【未解决】Mac中VSCode中Command+鼠标点击无法新建markdown文件
但是无法解决。
导致需要手动操作,一个个去新建对应文件。很是麻烦。效率很低。
突然想到,可以写Python脚本实现对应功能。
去写脚本
输入:
/Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/SUMMARY.md
输出:
/Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/
下面建立出对应的markdown文件
且文件内部,加上对应的 一级标题:
去写python
/Users/xxx/dev/crifan/gitbook/gitbook_template/common/tools/generate_md_from_summary.py
期间遇到:
【已解决】Python文件支持运行时从命令行传入参数
继续写代码调试:
到了kill
eachLine=* [kill](commands/process/kill.md)
mdName=kill, mdPath=commands/process/kill.md
输出:
Created md: /Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/commands/process/kill.md
去看看创建的文件:
是可以创建的。
是我们希望的。
继续:
。。。
mdName=数据恢复, mdPath=dev_summary/data_restore.md
Created md: /Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/dev_summary/data_restore.md
eachLine=* [模拟Linux系统](dev_summary/emulate_linux.md)
mdName=模拟Linux系统, mdPath=dev_summary/emulate_linux.md
Created md: /Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/dev_summary/emulate_linux.md
eachLine=* [附录](appendix/README.md)
mdName=附录, mdPath=appendix/README.md
Existed md: /Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/appendix/README.md
eachLine=* [参考资料](appendix/reference.md)
mdName=参考资料, mdPath=appendix/reference.md
Existed md: /Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/appendix/reference.md
去看看比较靠后的一个:
也是可以的。
不过,突然想到了:
额外加上功能:
当文件已存在,可以更新文件
-》使得文件最后更新时间是当前最新时间
-》且如果为了避免代码导致最后更新时间都一样,不像人工更新的,那么可以:
-》加上支持:更新的最后更新时间是,当前时间-一段时间(比如10分钟)- 当前时间
去加上参数支持
去实现:
【已解决】Python更新文件最后修改时间
【总结】
代码:
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function: Generate gitbook markdown files from entry md file SUMMARY.md. if md existed, update md file time.
Author: Crifan Li
Update: 20210509
"""


import argparse
import os
import re
from datetime import datetime
import random


argParser = argparse.ArgumentParser()
argParser.add_argument("-f", "--md-file", type=str, required=True, help="full path of entry SUMMARY.md file")
argParser.add_argument("--disable-update-existed-md", action='store_true', help="disable update existed md file modification time")
argParser.add_argument("--enable-use-random-time", action='store_false', help="enable use random time for update time")
argParser.add_argument("-r", "--random-range", type=int, default=10*60, help="for random time, the range. in seconds. default 600 = 10 minutes")
args = argParser.parse_args()


# if not args.file:
#     raise Exception("SUMMARY.md file required !")


summaryMdFullPath = args.md_file
# isUpdateMdWhenExist = args.update_existed_md
print("args.disable_update_existed_md=%s" % args.disable_update_existed_md)
isUpdateMdWhenExist = not args.disable_update_existed_md
isRandomUpdateTime = args.enable_use_random_time
randomRange = args.random_range


# # for debug
# summaryMdFullPath = "/Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/SUMMARY.md"
# isUpdateMdWhenExist = True
# isRandomUpdateTime = True
# randomRange = 10 * 60 # in seconds


print("summaryMdFullPath=%s" % summaryMdFullPath)
print("isUpdateMdWhenExist=%s" % isUpdateMdWhenExist)
print("isRandomUpdateTime=%s" % isRandomUpdateTime)
print("randomRange=%s" % randomRange)


bookRootPath = os.path.dirname(summaryMdFullPath)
print("bookRootPath=%s" % bookRootPath)


summaryMdLineList = open(summaryMdFullPath).readlines()
# print("summaryMdLineList=%s" % summaryMdLineList)


def updateFileTime(filePath, newAccessTime=None, newModificationTime=None, isAccessSameWithModif=True):
    """Update file access time and modification time


    Args:
        filePath (str): file path
        newAccessTime (int): new file access time, float
        newModificationTime (int): new file modification time, float
        isAccessSameWithModif (bool): make access same with modification 
    Returns:
        None
    Raises:
    Examples:
        newModificationTime=1620549707.664307
    """
    if (not newAccessTime) and (not newModificationTime):
        return
    
    statInfo = os.stat(filePath)
    # print("statInfo=%s" % statInfo)
    # print("statInfo.st_info=%s" % statInfo.st_info)


    if not newAccessTime:
        oldAccessTime = statInfo.st_atime # 1619490904.6651974
        # print("oldAccessTime=%s" % oldAccessTime)
        newAccessTime = oldAccessTime


    if not newModificationTime:
        oldModificationTime = statInfo.st_mtime # 1617002149.62217
        # print("oldModificationTime=%s" % oldModificationTime)
        newModificationTime = oldModificationTime


    if isAccessSameWithModif:
        newAccessTime = newModificationTime


    os.utime(filePath, (newAccessTime, newModificationTime))


summaryMdLineCount = len(summaryMdLineList)
print("Total md line count: %d" % summaryMdLineCount)
for curIdx, eachLine in enumerate(summaryMdLineList):
    curNum = curIdx +1
    print("%s %s %s" % ("-"*20, curNum, "-"*20))
    eachLine = eachLine.strip()
    # print("eachLine=%s" % eachLine)
    # * [Linux系统概述](linux_sys_overview/README.md)
    foundMd = re.search("\*\s+\[(?P<mdName>[^\]]+)\]\((?P<mdPath>[\w/]+\.md)\)", eachLine)
    if foundMd:
        mdName = foundMd.group("mdName")
        mdPath = foundMd.group("mdPath")
        print("mdName=%s, mdPath=%s" % (mdName, mdPath))


        mdAbsPath = os.path.join(bookRootPath, mdPath)


        mdFolderPath = os.path.dirname(mdAbsPath)
        if mdFolderPath:
            os.makedirs(mdFolderPath, exist_ok=True)


        if os.path.exists(mdAbsPath):
            # print("Existed md: %s" % mdAbsPath)
            print("Existed md: %s" % mdPath)
            if isUpdateMdWhenExist:
                curDateTime = datetime.now() # datetime.datetime(2021, 5, 9, 16, 41, 9, 399425)
                curTimestamp = curDateTime.timestamp() # 1620549669.399425
                if isRandomUpdateTime:
                    lessTime = random.randint(0, randomRange) # 13451
                    newModifTime = curTimestamp - lessTime # 1620554635.993749 -> 1620541184.993749
                else:
                    newModifTime = curTimestamp
                updateFileTime(mdAbsPath, newModificationTime=newModifTime)
                # print("Updated modifiy time for md: %s" % mdAbsPath)
                print("Updated modifiy time for md: %s" % mdAbsPath)
        else:
            with open(mdAbsPath, "w") as mdFp:
                titleMdStr = "# %s\n" % mdName
                mdFp.write(titleMdStr)
                # print("Created md: %s" % mdAbsPath)
                print("Created md: %s" % mdPath)
效果:
  • 没md,创建md
  • 有md,(默认开启)更新文件时间
    • (默认开启)且更新时间采用随机时间
    • 随机时间范围默认 前10分钟~当前时间
调用方式举例:
cd /Users/xxx/dev/crifan/gitbook/gitbook_template/common/tools

python generate_md_from_summary.py —help

python generate_md_from_summary.py --disable-update-existed-md --enable-use-random-time -f /Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/SUMMARY.md

python generate_md_from_summary.py --disable-update-existed-md -f /Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/SUMMARY.md

python generate_md_from_summary.py -f /Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/SUMMARY.md

python generate_md_from_summary.py --enable-use-random-time -r 1200 -f /Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/SUMMARY.md
最常用:
python generate_md_from_summary.py -f /Users/xxx/dev/crifan/gitbook/gitbook_template/books/linux_usage_dev_summary/src/SUMMARY.md
即可。

转载请注明:在路上 » 【已未解决】用Python从gitbook的markdown文件SUMMARY.md生成相关md文件

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.175 seconds, using 22.14MB memory