Python是一门解释型语言,当我们想让其他人运行我们的代码时,如果直接将.py源代码发送给他人,那么源代码将没有任何安全性可言,也就是任何一个人都可以打开源代码一看究竟,任何人都可以随意修改源代码。
而为了防止源代码泄露,可以将Python源代码编译生成.pyd库文件或者.so库文件:Windows平台生成pyd文件,Linux生成so文件。
py:Python控制台程序的源代码文件
pyw:Python带用户界面的源代码文件
pyx:Python包源文件
pyc:Python字节码文件(可通过逆向编译来得到源码)
pyo:Python优化后的字节码文件(可通过逆向编译来得到源码)
pyd:在Windows平台上Python的库文件(Python版DLL)
so:在Linux平台上Python的库文件是so文件
example:
hello.py
def say_hello():
print("Hello!")
pip3 install Cython
setup.py
from setuptools import setup
from Cython.Build import cythonize
# python3 setup.py build_ext --inplace
# 所有需要编译的py文件
all_py_file = ['hello.py']
setup(
name="hello",
ext_modules=cythonize(all_py_file),
version="1.0",
author="Leo",
author_email="[email protected]"
)
执行:python3 setup.py build_ext --inplace
pyd/so文件是由 Cython首先把python源码翻译成了 .c文件(这个过程基本不可逆),再把这个.c文件编译成了pyd/so文件。
pyinstaller是一个第三方库,它能够在Windows、Linux、 Mac OS X 等操作系统下将 Python 源文件打包,通过对源文件打包, Python 程序可以在没有安装 Python 的环境中运行,也可以作为一个 独立文件方便传递和管理。
Pyinstaller打包的可执行文件并不是跨平台的,而是希望在哪个平台上运行就需要在哪个平台上进行打包。
安装pyinstaller:
python3 -m pip install --no-cache-dir pyinstaller -i https://mirrors.aliyun.com/pypi/simple/;
main.py
from hello import say_hello
if __name__ == '__main__':
say_hello()
打包
pyinstaller --name say_hello --onedir --log-level WARN --strip --paths /leo/gme/pyinstaller_demo --distpath /leo/gme/pyinstaller_demo/package /leo/gme/pyinstaller_demo/main.py
Cpython可以将py编译成so文件,将编译好的so文件以原来的工程组织形式(module)存放好,注意module下要有非编译的__init__.py, 工程的main.py也不要编译
pyinstaller的打包过程会从main.py走一遍所有调用的module,并打包进去,但是编译好的pyd不会被识别import,这就是为什么要保留原来module的__init__.py, 对于这些已经编译为so的module,属于隐式import,需要在打包时加入–hidden-import
main.py
from hello import say_hello
if __name__ == '__main__':
say_hello()
打包
pyinstaller --hidden-import "hello" --name say_hello --onedir --log-level WARN --strip --paths /leo/gme/pyinstaller_demo --distpath /leo/gme/pyinstaller_demo/package /leo/gme/pyinstaller_demo/main.py
Cpython编译:https://www.cnblogs.com/gcgc/p/16529975.html
Pyinstaller介绍:https://blog.csdn.net/weixin_45953322/article/details/128774685
Pyinstaller打包so文件 https://blog.csdn.net/weixin_39916966/article/details/130781599