首页 > 代码库 > 使用cython把python编译so

使用cython把python编译so

1.需求

为了保证线上代码安全和效率,使用python编写代码,pyc可直接反编译,于是把重要代码编译so文件

2.工作

    2.1 安装相关库:

pip install cythonyum install -y gcc python-devel

   2.2 创建setup.py

#!/usr/bin/env python# coding=utf-8from distutils.core import setupfrom Cython.Build import cythonizesetup(    ext_modules = cythonize("xxxx.py"))

 2.3 运行

root@868aec72d1a4:/xxx/xxx/xxx# python setup.py build_extCompiling xxx.py because it changed.[1/1] Cythonizing xxx.pyrunning build_extbuilding lib.xxx extensioncreating buildcreating build/temp.linux-x86_64-2.7x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c xxx.c -o build/temp.linux-x86_64-2.7/xxx.ocreating build/lib.linux-x86_64-2.7creating build/lib.linux-x86_64-2.7/libx86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wl,-Bsymbolic-functions -Wl,-z,relro -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/xxx.o -o build/lib.linux-x86_64-2.7/lib/xxx.so

会在当年目录上传build目录,结构如下:

root@868aec72d1a4:/spider/codes/lib# tree build/build/|-- lib.linux-x86_64-2.7|   `-- lib|       `-- xxx.so`-- temp.linux-x86_64-2.7    `-- xxx.o3 directories, 2 files

 

2.4 获取so文件即可

 

使用cython把python编译so