import os
import py_compile
import zipfile
import datetime
def add_custom_folder_to_zip(custom_folder, zipf, base_path):
"""
将自定义文件夹添加到压缩文件中,保留原始目录结构。
:param custom_folder: 自定义文件夹路径
:param zipf: 压缩文件对象
:param base_path: 项目根目录,用于保持相对路径
"""
for root, dirs, files in os.walk(custom_folder):
for file in files:
full_path = os.path.join(root, file)
# 保留相对于项目根目录的路径结构
arcname = os.path.relpath(full_path, base_path)
zipf.write(full_path, arcname)
print(f"Added {file} from custom folder to zip: {arcname}")
def get_version(version_file_path):
"""从version.py文件中提取__version__的值"""
version = ""
with open(version_file_path, 'r', encoding='utf-8') as f:
for line in f:
if line.startswith("__version__"):
# 提取 __version__ 后面的值,去掉引号和空格
version = line.split('=')[1].strip().strip("'").replace(" ", "")
break
return version
def find_py(file_path, no_list, zipf):
# 遍历目录及其子目录,查找所有.py文件
for root, dirs, files in os.walk(file_path):
for file in files:
if file.endswith('.py'):
full_path = os.path.join(root, file)
# 如果是__init__.py或version.py文件,直接打包,不编译
if file == '__init__.py' or file == 'version.py':
arcname = os.path.relpath(full_path, file_path)
zipf.write(full_path, arcname)
print(f"Added {file} to zip: {arcname}")
continue
# 对其他.py文件进行编译处理
if file not in no_list:
try:
# 创建与.py文件对应的.pyc文件路径
pyc_file = file[:-3] + '.pyc' # 将.py替换为.pyc
pyc_path = os.path.join(root, pyc_file)
# 编译.py文件,直接生成与.py文件对应的.pyc文件
py_compile.compile(full_path, cfile=pyc_path, doraise=True)
# 在zip文件中保留原始目录结构
arcname = os.path.relpath(pyc_path, file_path)
zipf.write(pyc_path, arcname)
print(f"Added to zip: {arcname}")
# 删除源文件目录中的.pyc文件
os.remove(pyc_path)
except py_compile.PyCompileError as e:
print(f"Error compiling {full_path}: {e}")
def file_to_zip(src_dir, zip_name, custom_folder=None):
# 创建一个压缩文件
with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
# 查找并编译.py文件并将.pyc文件加入压缩包
no_list = ['PyToPyc.py'] # 可以将不需要编译的文件加入此列表
find_py(src_dir, no_list, zipf)
# 如果有自定义文件夹,则将该文件夹也添加到压缩包中
if custom_folder and os.path.exists(custom_folder):
add_custom_folder_to_zip(custom_folder, zipf, src_dir)
def main():
file_path = os.getcwd() # 当前项目根目录
print(f"Current directory: {file_path}")
# 获取文件路径的最后一级目录名称
folder_name = os.path.basename(file_path)
# 从 version.py 文件中提取版本号
version_file_path = os.path.join(file_path, 'version.py')
version = get_version(version_file_path)
# 获取当前日期并格式化为"年月日"格式
current_date = datetime.datetime.now().strftime('%y%m%d')
print(current_date)
# 生成zip文件名
zip_name = f"{folder_name}.{version}.build{current_date}.zip"
print(f"Generated zip name: {zip_name}")
# 自定义文件夹路径(使用完整路径,保留父目录结构)
custom_folder = os.path.join(file_path, './test/cccd/task')
# 创建压缩包并将.pyc文件、version.py、__init__.py文件和自定义文件夹打包进去
file_to_zip(file_path, zip_name, custom_folder=custom_folder)
print('All .pyc, version.py, __init__.py files and custom folder have been zipped.')
if __name__ == '__main__':
main()
标签:pyc,zip,py,version,file,path,folder,改进版
From: https://blog.51cto.com/u_16420155/12092180