python项目工程整体编译(cython)

应用场景:

1. pytho项目加密,so文件不可读,一定程度上可以保密编程代码
2. 计算能力加速,本质上编译过程为python -> c -> so文件,相当于动态语言转换为静态语言,程序执行能力和计算能力有所提升

实例

测试环境:ubuntu20.04 / python3.7

  1. 工程结构
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

  1. 编译脚本 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
    )
)
  1. 清理脚本 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
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值