首页 > 编程语言 >python3 批量编译pyc文件

python3 批量编译pyc文件

时间:2022-10-14 10:15:04浏览次数:54  
标签:__ join py 编译 path pyc os python3

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所在目录>

标签:__,join,py,编译,path,pyc,os,python3
From: https://www.cnblogs.com/czlnb/p/16790659.html

相关文章