利用Python將py檔案編譯成so檔案
- 1. 緣由
- 2. 辦法
- 2.1. 軟體環境
- 2.2. 源檔案
- 2.3. setup.py
- 2.4. 執行編譯
- 2.5. 使用
- 2.6. inplace
1. 緣由
Python的解釋特性是將py編譯為獨有的二進制編碼pyc檔案
然后對pyc中的指令進行解釋執行
但是pyc的反編譯卻非常簡單,可直接反編譯為原始碼
正所謂“防人之心不可無”
當需要將產品發布到外部環境的時候,原始碼的保護尤為重要
2. 辦法
可以先將py轉換為c,然后編譯c為so檔案
2.1. 軟體環境
安裝 cython
$ pip3 install cython
2.2. 源檔案
在py_to_so檔案夾下新建test.py檔案待編譯,內容如下:
class TEST:
def hello():
print('Hello CSDN!')
2.3. setup.py
在py_to_so檔案夾下新建setup.py檔案,內容如下:
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize(["test.py"]))
2.4. 執行編譯
在py_to_so檔案夾下執行編譯
$ python3 setup.py build_ext

運行后會生成build檔案夾,如下:

lib.linux-x86_64-3.8檔案夾下的test.cpython-38-x86_64-linux-gnu.so就是想要的.so檔案

2.5. 使用
現在so檔案就可以像普通py檔案一樣匯入使用
$ cd build/lib.linux-x86_64-3.8
$ python3
$ from test import TEST
$ TEST.hello()
# Hello CSDN!

2.6. inplace
$ python3 setup.py build_ext --inplace
–inplace:ignore build-lib and put compiled extensions into the source directory alongside your pure Python modules
忽略build-lib,將編譯后的擴展放到源目錄中,與Python模塊放在一起

文中所提檔案已在 CSDN代碼 codechina py_to_so 中
謝謝
CSDN認證博客專家
機器人軟體
運動控制
深度學習
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/265395.html
標籤:python
