目的:使用cpython加密成so文件,达到保密的目的,同时有加速的效果。
1、项目根目录创建文件,修改其中的忽略文件
setup.py
import os
import re
from distutils.core import Extension, setup
from Cython.Build import cythonize
from Cython.Compiler import Options
# 忽略文件
exclude_so = ['__init__.py', "setup.py", "main.py"]
# 目标目录
sources = ['./']
extensions = []
for source in sources:
for dir_path, folder_names, filenames in os.walk(source):
for filename in filter(lambda x: re.match(r'.*[.]py$', x), filenames):
print(filename)
file_path = os.path.join(dir_path, filename)
if filename not in exclude_so:
print("debug point ", file_path[:-3].replace('/', '.')[2:])
extensions.append(
Extension(file_path[:-3].replace('/', '.')[2:], [file_path], extra_compile_args=["-Os", "-g0"],
extra_link_args=["-Wl,--strip-all"]))
print("debug point 1")
Options.docstrings = False
compiler_directives = {'optimize.unpack_method_calls': False}
setup(
ext_modules=cythonize(extensions, exclude=None, nthreads=20, quiet=True, build_dir='./build',
language_level=3, compiler_directives=compiler_directives))
# python3 setup.py build_ext --inplace # 带inplace会把so文件生成到对应的目录,删除py即可。
2、编译
# 带inplace会把so文件生成到对应的目录,删除py即可。
python3 setup.py build_ext --inplace
# 如果不附带--inplace,会把so生成到build/lib.linux-x86_64-3.7目录下。整体考出来即可。
3、正常运行
python3 main.py