This file is modified based on the python compiler,for the record . Can be used for subsequent automated operations.
# -*- coding: UTF-8 -*-
# Desc: python project compilation file,This file is placed in the root directory of the compilation project, and the compilation project path can also be configured,For configuration, see TODO
# TODO
# 1. Set python version
# 2. Folders that need to be skipped
# 3. List of py files that do not need to be compiled
# 4 . Project path (default directory of the file)import os
import sys
import importlib.util
import py_compile
import struct__all__ = ["compile_dir", "compile_my_project"]def _walk_dir(dir, ddir=None, maxlevels= 10, quiet=0, exclude_dir=[], exclude_files=[]):if quiet < 2 and isinstance(dir, os.PathLike):dir = os. span>fspath(dir)if not quiet:print('Listing {!r}...'.format(dir))try:names = os.listdir (dir)except OSError:if quiet < 2:print("Can't list {!r}".format (dir))names = []names.sort()for name in names:if name == '__pycache__':continue# Exclude path if name in exclude_dir:continuefullname = os.path.join(dir, name )# Exclude files that are not required for compilationif name in exclude_files:print ("Non-compiled file:%s " % (name,)) print("Copy file:%s to %s " % (name, os.path.join(ddir, name))) _copy_file(fullname, os.path.join(ddir, name ))continue# non-py file if os.path.isfile(fullname) and not name.endswith(".py"):print ("non-py file:%s " % (name,)) print("Copy file:%s %s " % (fullname, os.path.join(ddir, name)))os .makedirs(ddir, exist_ok=True)_copy_file (fullname, os.path. join(ddir, name))continueif ddir is not None:dfile = os.path.join(ddir, name)else:dfile = Noneif not os.path .isdir(fullname):yield fullname, ddirelif (maxlevels > 0 and name != os.curdir and name != os.pardir andos.path.isdir(fullname) and not os.path.islink(fullname)):yield from span> _walk_dir(fullname, ddir= dfile,maxlevels=maxlevels - 1, quiet=quiet, exclude_dir=exclude_dir,exclude_files=exclude_files)def compile_dir(dir, maxlevels=10, ddir=None, force= ;False, rx=None,quiet=0, legacy=False, optimize=-1,invalidation_mode=None, exclude_dir=[],exclude_files= ;[]):"""Byte-compile all modules in the given directory tree.Arguments (only dir is required):dir: the directory to byte-compilemaxlevels: maximum recursion level (default 10)ddir: the directory that will be prepended to the path to thefile as it is compiled into each byte-code file.force: if True, force compilation, even if timestamps are up -to-datequiet: full output with False or 0, errors only with 1,no output with 2legacy: if True, produce legacy pyc paths instead of PEP 3147 pathsoptimize: optimization level or -1 for level of the interpreterworkers: maximum number of parallel workersinvalidation_mode: how the up-to-dateness of the pyc will be checkedexclude_dir: File directory that will not be compiledexclude_files: Files that will not be compiled"""files_and_ddirs = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels,ddir=ddir__class__.__name__ + ':& #39;, e)else :if ok == 0:success = Falsereturn successdef _copy_file(from_file, to_file):# Copy fileos.system("cp %s %s " % (from_file, to_file))def _check_python_version(version):# Check the python environment versionif version == sys.version .split(" ")[0] :return Trueraise Exception(f"The python environment version is wrong,The expected version is {version}")def compile_my_project(python_version, project_home=None,exclude_dirs=[ "migrations", ],exclude_files =["manage.py", "asgi.py", "wsgi.py", "settings.py"]):""": param python_version: python version: param project_home: project path (default directory of the file): param exclude_dirs: folders that need to be skipped: param exclude_files: list of py files that do not need to be compiled: return: """ # 1. Check the python environment version_check_python_version(python_version )# Parse the project path (the folder path where the file is stored)if not project_home:project_home = os.path.dirname(os.path.abspath(__file__))exclude_files.append(os .path.basename(os. path.abspath(__file__)))# Project folder nameproject_name = project_home.split(os. sep)[-1]##=== Compile file Storage path (put it in the same directory as the project path,New {project_name}_compile/{project_name})project_compile_home = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),project_name + '_compile', project_name)print("Compile source file path:" , project_home)print("Compile file storage path:", project_compile_home)os.makedirs(project_compile_home, exist_ok=True) compile_dir(dir= project_home, ddir=project_compile_home, force=True, exclude_dir=exclude_dirs,exclude_files=exclude_files)print("&# 61;====The compilation project is completed. . . ")if __name__ == ; '__main__':# This file is placed in the root directory of the compiled project# Compiled file storage path (placed in the same directory as the project path,New {dir_name}_compile/{dir_name })# 0. TODO Set python versionMY_PROJECT_PYTHON_VERSION = "3.6.10"# 0. TODO Folder to be skippedexclude_dir = ["migrations", ]# 0. TODO list of py files that do not need to be compiledexclude_files = ["manage.py", "asgi.py", "wsgi.py", "settings.py", "settings_prd.py"]compile_my_project(MY_PROJECT_PYTHON_VERSION, exclude_dirs=exclude_dir, exclude_files =exclude_files)
># Project folder nameproject_name = project_home.split(os.sep)[–1]##=== Compile file storage path (place it in the same directory as the project path,New {project_name}_compile/ {project_name})project_compile_home = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),project_name + '_compile', project_name)print(“Compile source file path:”, project_home)print(“Compile File storage path:”, project_compile_home)os.makedirs(project_compile_home, exist_ok= True)compile_dir(dir=project_home, ddir=project_compile_home, force=True, exclude_dir=exclude_dirs ,exclude_files=exclude_files)print(“Compilation project completed. . . “)if __name__ == ; '__main__':# This file is placed in the root directory of the compiled project# Compiled file storage path (placed in the same directory as the project path,New {dir_name}_compile/{dir_name })# 0. TODO Set python versionMY_PROJECT_PYTHON_VERSION = “3.6.10”# 0. TODO Folder to be skippedexclude_dir = [“migrations”, ]# 0. TODO list of py files that do not need to be compiledexclude_files = [“manage.py”, “asgi.py”, “wsgi.py”, “settings.py”, “settings_prd.py”]compile_my_project(MY_PROJECT_PYTHON_VERSION, exclude_dirs=exclude_dir, exclude_files =exclude_files)
xclude_files)