应用场景:
1. pytho项目加密,so文件不可读,一定程度上可以保密编程代码
2. 计算能力加速,本质上编译过程为python -> c -> so文件,相当于动态语言转换为静态语言,程序执行能力和计算能力有所提升
实例
测试环境:ubuntu20.04 / python3.7
- 工程结构
test_project:
- app
- business
- t1.py
- t2.py
- common
- middleware.py
- cache
- cache.py
- models
- t1.py
- t2.py
- views
- t1.py
- t2.py
- app.py
- config
- config.py
- logger.py
- compile.py
- build.sh
- 编译脚本
compile.py
from setuptools import setup
from setuptools.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
setup(
ext_modules=cythonize(
[
Extension('app.*', ['app/*.py']),
Extension('app.business.*', ['app/business/*.py']),
Extension('app.common.*', ['app/common/*.py']),
Extension('app.common.cache.*', ['app/common/cache/*.py']),
Extension('app.models.*', ['app/models/*.py']),
Extension('app.views.*', ['app/views/*.py']),
Extension('config.*', ['config/*.py']),
],
build_dir='build',
compiler_directives=dict(
always_allow_keywords=True, language_level=3
)
),
cmdclass=dict(
build_ext=build_ext
)
)
- 清理脚本
build.sh
#!/bin/sh
set -e
# 清除缓存
find . -type d -name __pycache__ | xargs rm -rf
# 编译代码
sh env/bin/activate
python compile.py build_ext --inplace
if [ $? -ne 0 ]; then
exit 1
fi
# so文件重命名
find ./app -name '*.so' | awk -F '.cpython-*-linux-gnu' '{print "mv "$0" "$1$2}' | sh
find ./config -name '*.so' | awk -F '.cpython-*-linux-gnu' '{print "mv "$0" "$1$2}' | sh
# 删除py文件
find ./app -name '*.py' | xargs rm -f
find ./config -name '*.py' | xargs rm -f