使用cython把python编译so

1.需求

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

2.工作

    2.1 安装相关库:

pip install cython
yum install -y gcc python-devel

   2.2 创建setup.py

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

 2.3 运行

root@868aec72d1a4:/xxx/xxx/xxx# python setup.py build_ext
Compiling xxx.py because it changed.
[1/1] Cythonizing xxx.py
running build_ext
building 'lib.xxx' extension
creating build
creating build/temp.linux-x86_64-2.7
x86_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.o
creating build/lib.linux-x86_64-2.7
creating build/lib.linux-x86_64-2.7/lib
x86_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.o

3 directories, 2 files

 

2.4 获取so文件即可

 

posted @ 2017-07-12 11:42  sevck  阅读(6797)  评论(0编辑  收藏  举报