应用场景
Python是一种面向对象的解释型计算机程序设计语言,具有丰富和强大的库,使用其开发产品快速高效。
python的解释特性是将py
编译为独有的二进制编码pyc
文件,然后对pyc
中的指令进行解释执行,但是pyc
的反编译却非常简单,可直接反编译为源码,当需要将产品发布到外部环境的时候,源码的保护尤为重要.
准备工作
环境是可为linux/centos
,我 Windows10 本地是 Bash on Ubuntu on Windows,用起来很方便,命令行打bash即进入命令行
思路是先将py
转换为c
代码,然后编译c
为so
文件
要安装以下内容
python 安装: cython
pip install cython
linux 安装: python-devel,gcc
yum install python-devel
yum install gcc
1. 使用cythonize函数
新建如下目录结构:
test/
├── hello.py
└── setup.py
文件内容如下:
hello.py :
def hello():
print('hello!')
setup.py :
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize(["hello.py"]))
然后执行以下命令:
python setup.py build_ext
然后新生成的 build/lib*/hello.so
目录下的就是我们想要的。
进入到 build/lib*
目录,执行 python
>>> import hello
>>> hello.hello()
hello!
2. 使用cython提供的build_ext
更改setup.py
为:
from distutils.core import setup
from Cython.Distutils import build_ext
from distutils.extension import Extension
setup(
ext_modules = [Extension('hello', ['hello.py'])],
cmdclass = {'build_ext': build_ext},
)
其余步骤和上面一样。