保护python源代码,将python代码编译成.so文件

关于C与python的关系:https://moonlet.gitbooks.io/cython-document-zh_cn/content/ch1-basic_tutorial.html

前提:必须安装好Cython库

pip install Cython

1、准备好adds.pyx文件(注意是pyx文件,而不是py)

def adds(listA):
    total = 0.
    for   elm in listA:
        total += elm
    return total

2、准备好封装文件setup.py

from distutils.core import setup
from Cython.Build import cythonize
 
setup(
    ext_modules = cythonize("adds.pyx")
)

3、进行封装

python2  setup.py build_ext --inplace
#如果是python3 那就打python3,只需要对应的python版本安装了Cypython即可

4、获得的adds.so就是封装后的文件,将该adds.so文件复制到对应的库文件中即可直接import使用

比如本次我们将adds.so文件复制到python2的库文件目录中  /usr/lib/python2.7/site-packages,之后就可以直接import adds

5、运行并调用封装后的adds模块

 此时adds.so打开是乱码的。

原文地址:https://www.cnblogs.com/mrtop/p/13443275.html