python必备源代码-python 源代码保护 之 xx.py -> xx.so
前情提要
之前由于项目的需要,需要我们将一部分"关键代码”隐藏起来。
虽然Python 先天支持 将源代码 编译后 生成 xxx.pyc 文件,但是**起来相当容易 -_-!!
于是搜罗到了另外一种方法,将关键的代码文件/库 转换成 .so ,从而将其保护起来。
使用 Cython 保护代码 ( 测试环境为:Ubuntu16.04 - LTS)
① 准备工作
1. 安装 cython
pip install cython
2. 安装 python-dev
sudo apt-get install python-dev
3. 安装gcc
sudo apt-get install gcc
② 新建setup.py,内容如下
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules= cythonize(["Train_predict.py"]))
③ 运行脚本 (注: 需要在Python 文件的同目录下运行)
python setup.py build_ext
④ 运行脚本后,在当前目录会生成一个 /build 子目录
打开后,可以看到 .so 文件已经生成:
将 .so 文件拷贝到原来 .py 文件的目录后,删除 .py文件;测试: 在没有修改任何调用程序源码的情况下,在pythoncharm中已经无法找到 "Train_predict.py” 中函数的定义,但是却可以正常的调用这个函数。
OK, 我们已经成功地将"关键代码” 隐藏起来; 任务完成!!
最后,感谢大家的观看,欢迎留言讨论哦 :)
参考:
http://fengzheng369.blog.163.com/blog/static/7522097920161253407914
http://www.cnblogs.com/ke10/p/py2so.html
补充
今天在网上查了下资料,发现可以一次编译多个.py文件为 .so
from distutils.core import setup
from Cython.Build import cythonize
#setup(
#ext_modules= cythonize("Train_predict.py")
#)
setup(
ext_modules= cythonize(["SCIPinterface.py", "normalize.py"])
)
我们注意到可以用 list 作为cythonize的参数来传入,于是,这里尝试着传递了2个新的Python源程序文件 ("SCIPinterface.py", "normalize.py")
生成对应的 .so 文件以及terminal如下所示:
Done ~~
叒 一次的补充
现在我们已经可以生成变异后的 .so 文件了,但是每次编译生成的 临时文件(例如.c)然后处理起来很麻烦!!, 于是发现了另一个好东西,这里搬运过来。 也感谢原文的作者为大家打来的福音!!
集成编译
最新代码github:https://github.com/ArvinMei/py2so.git
做了以下内容:
1.文件夹编译
2.删除编译出的.c文件
3.删除编译的temp文件夹
#-* -coding: UTF-8 -* -__author__= 'Arvin'
"""执行前提:
系统安装python-devel 和 gccPython安装cython
编译整个当前目录:
python py-setup.py
编译某个文件夹:
python py-setup.py BigoModel
生成结果:
目录 build 下
生成完成后:
启动文件还需要py/pyc担当,须将启动的py/pyc拷贝到编译目录并删除so文件"""import sys, os, shutil,timefrom distutils.core import setup
from Cython.Build import cythonize
starttime= time.time()
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"def getpy(basepath=os.path.abspath('.'), parentpath='', name='', excepts=(), copyOther=False,delC=False):"""获取py文件的路径
:param basepath: 根路径
:param parentpath: 父路径
:param name: 文件/夹
:param excepts: 排除文件
:param copy: 是否copy其他文件
:return: py文件的迭代器""" fullpath = os.path.join(basepath, parentpath, name)for fname inos.listdir(fullpath):
ffile= os.path.join(fullpath, fname)
#print basepath, parentpath, name,file
if os.path.isdir(ffile) and fname != build_dir and not fname.startswith('.'):for f in getpy(basepath, os.path.join(parentpath, name), fname, excepts, copyOther, delC):
yield felifos.path.isfile(ffile):
ext= os.path.splitext(fname)[1]if ext == ".c":if delC and os.stat(ffile).st_mtime >starttime:
os.remove(ffile)elif ffile not in excepts and os.path.splitext(fname)[1] not in('.pyc', '.pyx'):if os.path.splitext(fname)[1] in('.py', '.pyx') and not fname.startswith('__'):
yield os.path.join(parentpath, name, fname)elifcopyOther:
dstdir= os.path.join(basepath, build_dir, parentpath, name)ifnot os.path.isdir(dstdir): os.makedirs(dstdir)
shutil.copyfile(ffile, os.path.join(dstdir, fname))else:
pass
#获取py列表
module_list= list(getpy(basepath=currdir,parentpath=parentpath, excepts=(setupfile)))
try:
setup(ext_modules= cythonize(module_list),script_args=["build_ext", "-b", build_dir, "-t", build_tmp_dir])
except Exception, ex:
print"error!", ex.messageelse:
module_list= list(getpy(basepath=currdir, parentpath=parentpath, excepts=(setupfile), copyOther=True))
module_list= list(getpy(basepath=currdir, parentpath=parentpath, excepts=(setupfile), delC=True))ifos.path.exists(build_tmp_dir): shutil.rmtree(build_tmp_dir)
print"complate! time:", time.time()-starttime, 's'
这样,我们就可以和麻烦的临时文件 say goodbye 啦 ~~