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

yipeiwu_com5年前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设计】。

相关文章

Pandas Shift函数的基础入门学习笔记

Pandas Shift函数基础 在使用Pandas的过程中,有时会遇到shift函数,今天就一起来彻底学习下。先来看看帮助文档是怎么说的: >>> import...

python SVD压缩图像的实现代码

python SVD压缩图像的实现代码

前言 利用SVD是可以对图像进行压缩的,其核心原因在于,图像的像素之间具有高度的相关性。 代码 # -*- coding: utf-8 -*- ''' author@cclplu...

python 分离文件名和路径以及分离文件名和后缀的方法

分离路径和文件名: os.path.split() 区分文件的名字和后缀: os.path.splitext() import os file_path = "D:/test/t...

python使用scrapy发送post请求的坑

使用requests发送post请求 先来看看使用requests来发送post请求是多少好用,发送请求 Requests 简便的 API 意味着所有 HTTP 请求类型都是显而易见的...

python实现给微信公众号发送消息的方法

本文实例讲述了python实现给微信公众号发送消息的方法。分享给大家供大家参考,具体如下: 现在通过发微信公众号信息来做消息通知和告警已经很普遍了。最常见的就是运维通过zabbix调用s...