提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
`提示
例如:
提示:以下是本篇文章正文内容,下面案例可供参考
一、使用步骤
1.引入库
代码如下(示例):
python
# -*- coding:utf-8 -*-
# author: cbj
# datetime: 2024/7/1 16:49
# @File: 133打包python项目so文件.py
#
import copy
from pathlib import Path
import os
from pathlib import Path
from distutils.core import setup
from Cython.Build import cythonize
ignore_dir_name = ['migrations', '__pycache__', 'static', '.idea']
ignore_suffix = ['.csv', '.xlsx', '.doc', '.docx']
ignore_file = ['manage.py', "main_new.py", "main_new2.py", "main.py", "clean.py", "jiami.py", "simplepro.lic", "jiami2.py"]
delete_suffix = ['.c', '.py', '.pyc', '.o', ]
def get_all_py_files(dir_root):
"""获取所有的py文件,要编译成so的文件
:params dir_root: 项目根目录地址
"""
res_py_file_list = []
for root, dirs, files in os.walk(dir_root):
dirs1 = copy.deepcopy(dirs)
for i in ignore_dir_name:
if i in dirs1:
dirs.remove(i)
continue
for file in files:
# 不是py文件的 不转so
if os.path.splitext(file)[1] != '.py':
continue
# 某些特定文件不转so
if file in ignore_file:
continue
_path = f'{root}/{file}'
res_py_file_list.append(_path)
# print(f'====res_py_file_list:{res_py_file_list}')
return res_py_file_list
def py_to_so(project_dir=None, build_dir=None, build_tmp_dir=None):
"""
生成 .so文件
:return:
"""
# project_dir = './'
# build_dir = './'
# build_tmp_dir = './'
project_dir = project_dir
build_dir = build_dir
build_tmp_dir = build_tmp_dir
res_py_file_list = get_all_py_files(project_dir)
setup(ext_modules=cythonize(res_py_file_list, language_level="3"),
script_args=["build_ext", "-b", build_dir, "-t", build_tmp_dir])
# 删除原始项目py文件
def clean_c_file(dir_root='./'):
deletefiles = []
for root, dirs, files in os.walk(dir_root):
dirs1 = copy.deepcopy(dirs)
for i in ignore_dir_name:
if i in dirs1:
dirs.remove(i)
continue
for file in files:
# 不需要转so 也不需要删除的文件
if file in ignore_file:
continue
# 不需要转so 也不需要删除的文件
if Path(file).suffix in ignore_suffix:
continue
if os.path.splitext(file)[1] in delete_suffix:
_path = f'{root}/{file}'
deletefiles.append(_path)
# os.remove(_path)
# print(f'deletefiles==={deletefiles}')
for r1 in deletefiles:
os.remove(r1)
if __name__ == '__main__':
"""
参考地址:
https://xie.infoq.cn/article/9644cb3920e5163c4ec19d958
https://xie.infoq.cn/article/db31ccde7cbaad84a07aaec57
使用步骤 1 生成 .so文件 py_to_so()
2 清除原始项目文件和不需要文件 clean_c_file
"""
# pa = r'D:\data1\20240701\jiami\20240110\data_augmentation20230914\data_augmentation'
pa = './'
py_to_so(project_dir=pa, build_dir=pa, build_tmp_dir=pa)
# clean_c_file(pa)
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容