From 027c5078d35847acb75a086e68db3d2768550b1a Mon Sep 17 00:00:00 2001 From: shaohuzhang1 Date: Mon, 23 Dec 2024 19:18:53 +0800 Subject: [PATCH] build: compile-pyc --- installer/compile.py | 67 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 59 insertions(+), 8 deletions(-) diff --git a/installer/compile.py b/installer/compile.py index 4009e24668e..fc1413caabe 100644 --- a/installer/compile.py +++ b/installer/compile.py @@ -7,29 +7,80 @@ @desc: """ import os +import sys +import shutil from py_compile import compile +def clean(path_str: str): + for parent, dir_name, filename in os.walk(path_str): + for dir_str in dir_name: + if dir == '__pycache__': + fullname = os.path.join(parent, dir_str) + try: + shutil.rmtree(fullname) + print("Success clean Folder:%s" % fullname) + except Exception as e: + print("Can't clean Folder:%s, reason:%s" % (fullname, e)) + + def compile_pyc(path_str: str): - """ - 将py编译为pyc文件 - @param path_str: 需要编译的目录 - @return: None - """ for parent, dir_name, filename in os.walk(path_str): for cfile in filename: fullname = os.path.join(parent, cfile) if cfile[-3:] == '.py': try: - if compile(fullname, fullname.replace('py', 'pyc')): + if compile(fullname): if cfile != 'settings.py' and cfile != 'wsgi.py': os.remove(fullname) # 删除原文件,保留settings.py和wsgi.py - print("Success compile and remove file:%s" % fullname) + print("Success compile and remove file:%s" % fullname) else: print("Can't compile file:%s,The original file has been retained" % fullname) except Exception as e: print("Can't compile file:%s, reason:%s" % (fullname, e)) +def move(path_str: str): + for parent, dir_name, filename in os.walk(path_str): + for c_file in filename: + fullname = os.path.join(parent, c_file) + if c_file[-4:] == '.pyc': + try: + if parent.endswith('__pycache__'): + parent_path = os.path.dirname(parent) + shutil.move(fullname, parent_path) + print('update the dir of file successfully') + except Exception as e: + print("Can't move file:%s, reason:%s" % (fullname, e)) + + +def replace_name(path_str: str): + for parent, dir_name, filename in os.walk(path_str): + for c_file in filename: + fullname = os.path.join(parent, c_file) + if c_file[-4:] == '.pyc': + try: + cfile_name = '' + cfile_list = c_file.split('.') + version = sys.version_info + replace_name_str = 'cpython-' + str(version[0]) + str(version[1]) + for i in range(len(cfile_list)): + if cfile_list[i] == replace_name_str: + continue + cfile_name += cfile_list[i] + if i == len(cfile_list) - 1: + continue + cfile_name += '.' + shutil.move(fullname, os.path.join(parent, cfile_name)) + print('update the name of the file successfully') + except Exception as e: + print("Can't remove file:%s, reason:%s" % (fullname, e)) + + if __name__ == '__main__': - compile_pyc("../apps") + path = "/opt/maxkb/app/apps" + clean(path) + compile_pyc(path) + move(path) + replace_name(path) + clean(path)