此博客是演示如何將python代碼打包成so,防止python源碼泄露,保證代碼安全。以helloworld.py爲例,將python打包成so。
1.在/opt/目錄下編寫需要被編譯的代碼helloworld.py
#!/usr/bin/env python
# encoding: utf-8
def hello(name):
print("Hello %s!" % name)
2.在/opt/目錄下編寫Cython編譯所需要的setup.py文件
#!/usr/bin/env python
# encoding: utf-8
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = 'Hello world app',
ext_modules = cythonize("/opt/helloworld.py"),
)
如下所示
3.在/opt/目錄下執行Cython的編譯命令
python3 setup.py build_ext --inplace
多出綠色方框的文件
4. 創建一個調用so文件的pyhton文件,測試編譯後的so是否正常工作的代碼run.py
#!/usr/bin/env python
# encoding: utf-8
from helloworld import hello
hello('deamon ')
5.刪除build文件夾以及helloworld.c
6.運行測試代碼run.py