Cython编译python为so 代码加密示例

yipeiwu_com6年前Python基础

1. 编译出来的so比网上流传的其他方法小很多。

2. language_level  是python的主版本号,如果python版本是2.x,目前的版本Cython需要人工指定language_level.

3. python setup.py build_ext --inplace  执行脚本

4. 以下是代码片段

from distutils.core import Extension, setup
 
from Cython.Build import cythonize
from Cython.Compiler import Options
 
 
# __file__ 含有魔术变量的应当排除,Cython虽有个编译参数,但只能设置静态。
exclude_so = ['__init__.py', "mixins.py"]
sources = ['core', 'libs']
 
 
extensions = []
for source in sources:
  for dirpath, foldernames, filenames in os.walk(source):
    for filename in filter(lambda x: re.match(r'.*[.]py$', x), filenames):
      file_path = os.path.join(dirpath, filename)
      if filename not in exclude_so:
        extensions.append(
            Extension(file_path[:-3].replace('/', '.'), [file_path], extra_compile_args = ["-Os", "-g0"],
                 extra_link_args = ["-Wl,--strip-all"]))
 
 
Options.docstrings = False
compiler_directives = {'optimize.unpack_method_calls': False}
setup( 
    # cythonize的exclude全路径匹配,不灵活,不如在上一步排除。
    ext_modules = cythonize(extensions, exclude = None, nthreads = 20, quiet = True, build_dir = './build',
                language_level = 2 或者3 , compiler_directives = compiler_directives))

以上这篇Cython编译python为so 代码加密示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现的一个简单LRU cache

起因:我的同事需要一个固定大小的cache,如果记录在cache中,直接从cache中读取,否则从数据库中读取。python的dict 是一个非常简单的cache,但是由于数据量很大,内...

Python自定义进程池实例分析【生产者、消费者模型问题】

本文实例分析了Python自定义进程池。分享给大家供大家参考,具体如下: 代码说明一切: #encoding=utf-8 #author: walker #date: 2014-05...

Python高级特性——详解多维数组切片(Slice)

(1) 我们先用arange函数创建一个数组并改变其维度,使之变成一个三维数组: >>> a = np.arange(24).reshape(2,3,4) >...

使用django的ORM框架按月统计近一年内的数据方法

如下所示: # 计算时间 time = datetime.datetime.now() - relativedelta(years=1) # 获取近一年数据 one_year_dat...

Python+Selenium使用Page Object实现页面自动化测试

  Page Object模式是Selenium中的一种测试设计模式,主要是将每一个页面设计为一个Class,其中包含页面中需要测试的元素(按钮,输入框,标题 等),这样在Se...