python3 批量编译pyc文件

compile.py

import os, shutil
import compileall
import sys
import re

def copy_to_up(path):
    for f in os.listdir(path):
        if f == '__pycache__':
            for f_main in os.listdir(os.path.join(path, f)):
                path_src = os.path.join(path, f)
                shutil.copy(os.path.join(path_src, f_main), path)


def rename_file(path):
    for f in os.listdir(path):
        f = os.path.join(path, f)
        if f.endswith('.pyc') and '.cpython-3' in f:
            cpython =  re.search('.cpython-3.',f).group()
            f_new = f.replace(cpython, '')
            if os.path.exists(f_new):
                os.remove(f_new)
            os.rename(f, f_new)


def copy_rename(f, path):
    # 如果是__pycache__ 文件夹 将其中的文件移至上一层
    if f == '__pycache__':
        copy_to_up(path)
        # 当前层为.pyc文件重命名
        rename_file(path)
        shutil.rmtree(os.path.join(path,f))
    for pyf in os.listdir(path):
        if pyf.endswith('.py') and not os.path.isdir(os.path.join(path, pyf)):
            os.remove(os.path.join(path, pyf))


def py_to_pyc(path):
    if os.path.isdir(path):
        for f in os.listdir(path):
            copy_rename(f, path)
            if f != 'env' and f != '.vscode' and os.path.isdir(os.path.join(path, f)):
                path_d = os.path.join(path, f)
                py_to_pyc(path_d)
    else:
        print("你输入的不是有效文件夹")


if __name__ == '__main__':
    for path in sys.argv[1:]:
        compileall.compile_dir(path, force=True)
        py_to_pyc(path)

命令行执行下面的语句即可(注意此程序会删除py文件,记得备份)

python compile.py <py所在目录>
posted @ 2022-10-14 09:56  乘舟凉  阅读(214)  评论(0编辑  收藏  举报