当前位置: 移动技术网 > IT编程>脚本编程>Python > 使用Cython将py编译成.so文件

使用Cython将py编译成.so文件

2020年03月19日  | 移动技术网IT编程  | 我要评论

精品网页,甄嬛传mp4下载,潜江人论坛

目的

将python代码编译成pyd文件,以保护代码。(注,只能单个py文件生成单个pyd文件,windows下为pyd文件,linux下为so文件)

网上找到一篇相关的博文 使用cython将py编译成.so文件 ,从介绍、环境、注意事项、代码步骤注释得十分详细,因为代码不太符合自己的要求,因此基于该文代码重新写了一份代码。

对比实现

代码要求:

  1. 将所有需要生成的pyd文件复制到build目录下(已有)
  2. 将所有其他文件复制到build目录下(修改为所有不生成pyd的文件,原文只支持py文件)
  3. 忽略文件及文件夹,文件夹路径支持多级目录(新增文件夹,改写忽略文件为相对路径,所有路径均为相对路径)

代码步骤(同):

  1.  获取需要加密的py列表; 
  2.  cython先将py转换为c代码, 然后编译c为.o及.so文件; 
  3.  复制其他文件到./build 目录下;
  4.  删除临时文件

注意事项:

  1. __开头文件不能生成pyd文件,会报错
  2. 引入pyd报错时可用py文件替换

源代码(放在项目根目录下):

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @file  : build.py
# @author: wade cheung, editby bh liu
# @date  : 2019/2/23
# @desc  : 使用cython.build.cythonize将py编译成.so文件


import sys
import os
import shutil
from distutils.core import setup
from cython.build import cythonize

currdir = os.path.abspath('.') + '\\'
parentpath = sys.argv[1] if len(sys.argv) > 1 else ""
setupfile = os.path.join(os.path.abspath('.'), __file__)
build_dir = "build"
build_tmp_dir = build_dir + "/temp"

filter_dir_set = {'dist', 'build', 'config', 'data', 'const', 'test', 'orm\\data_init'}

except_files = {
    __file__,
    'build.py',
    'build_load_db.py',
    'main.py',
    'frozen_dir.py',
    'utils\\time_it.py',
}


def filter_file(file_name):
    if file_name.__contains__(currdir):
        file_name = file_name.replace(currdir, '')
    if file_name in except_files:  # 过滤文件
        return true
    file_path = file_name.split("\\")
    if len(file_path) > 1:
        file_dir = ""
        for i in range(len(file_path)-1):
            file_dir = os.path.join(file_dir, file_path[i])
            if file_dir in filter_dir_set:
                return true
    return file_path[0] in filter_dir_set


def getpy(basepath=os.path.abspath('.'), parentpath='', name='',
          copyother=false, delc=false):
    """
    获取py文件的路径
    :param basepath: 根路径
    :param parentpath: 父路径
    :param name: 文件/夹
    :param copy: 是否copy其他文件
    :return: py文件的迭代器
    """
    fullpath = os.path.join(basepath, parentpath, name)
    for fname in os.listdir(fullpath):
        ffile = os.path.join(fullpath, fname)
        if os.path.isdir(ffile) and fname != build_dir and not fname.startswith('.'):
            for f in getpy(basepath, os.path.join(parentpath, name), fname,
                          copyother, delc):
                yield f
        elif os.path.isfile(ffile):
            ext = os.path.splitext(fname)[1]
            # 删除.c 临时文件
            if ext == ".c":
                if delc:
                    os.remove(ffile)
            elif not filter_file(ffile) and (ext not in ('.pyc', '.pyx')
                                             and ext in ('.py', '.pyx')
                                             and not fname.startswith('__')):
                yield os.path.join(parentpath, name, fname)
            elif copyother and ext not in ('.pyc', '.pyx'):  # 复制其他文件到./build 目录下
                dstdir = os.path.join(basepath, build_dir, parentpath, name)
                if not os.path.isdir(dstdir):
                    os.makedirs(dstdir)
                shutil.copyfile(ffile, os.path.join(dstdir, fname))
        else:
            pass


# 获取py列表
module_set = set(getpy(basepath=currdir, parentpath=parentpath))

## 编译成.so文件
try:
    setup(ext_modules=cythonize(module_set, language_level=3),
          script_args=["build_ext", "-b", build_dir, "-t", build_tmp_dir])
    pass
except exception as ex:
    print("error! ", str(ex))
else:
    # 复制其他文件到./build 目录下
    getpy(basepath=currdir, parentpath=parentpath, copyother=true)

# 删除临时文件 ~
getpy(basepath=currdir, parentpath=parentpath, delc=true)


if os.path.exists(build_tmp_dir):
    shutil.rmtree(build_tmp_dir)

print("done !")

 

 

 

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网