zoukankan      html  css  js  c++  java
  • Python加密成.so或dll

    Python加密

    如何封装Python代码,让别人方便调用,同时又能起到加密的作用,本文介绍如何封装成so文件和dll文件以及调用方式

    • 首先需要配置环境 安装Cython gcc

    Linux下的.so文件

    • 创建要封装的文件mytest.py
    import datetime
    class DataCenter():
        def gettime(self):
            print(datetime.datetime.now())
        def write_data(self):
            print("hello XiaoBei!")
    
    • 创建调用文件 so_test.py
    from mytest import DataCenter
     
    data = DataCenter()
    data.gettime()
    data.write_data()
    

    运行so_test.py,证明程序正常

    • 创建打包文件 setup.py
    from distutils.core import setup
    from Cython.Build import cythonize
    #[]内是要打包的文件名,也可多个文件
    setup(ext_modules = cythonize(["mytest.py"]))
    
    • 执行python3 setup.py build_ext

    在当前目录下生成build文件夹和mytest.c文件,.so文件就在build文件夹内

    • 将so_test.py文件放到so目录下,运行,即可得到结果

    Windows下将Python封装成pyd文件

    pyd就是dll

    • mytest.py 和dll_test.py和上面一样
    • 创建setupDll.py
    # !/usr/bin/env python
    # -*- coding: utf-8 -*-
    from distutils.core import setup
    from Cython.Build import cythonize
    from distutils.extension import Extension
    
    def main():
        # 这里为文件名 可以增加多个Extension('  ', ['  '])
        extensions = [Extension('mytest', ['mytest.py'])]
        setup(ext_modules=cythonize(extensions))
    
    if __name__ == '__main__':
        main()
    
    • 在pycharm的terminal下输入Python setupDll build_ext,得到pyd文件

    • 在build文件夹下得到.pyd文件调用方式不变
    # !/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    #如果不想改变pyd路径,则需要在dll_test.py中加入:
    import sys
    sys.path.append('./build/lib.win-amd64-3.7/')
    from mytest import DataCenter
    def main():
        data = DataCenter()
        data.gettime()
        data.write_data()
    
    if __name__ == '__main__':
        main()   
    
    • 运行得到结果
  • 相关阅读:
    Android 通过ViewFlipper实现广告轮播功能并可以通过手势滑动进行广告切换
    [C#][DevPress]自定义数据分页控件
    [C#][SQLLITE]一个数据分页技巧
    [C#]用SharpZipLib压缩多个文件
    [C#][DevPress]省市县乡嵌套查询
    [C#][DevPress]事件委托的使用
    [C#]Excel操作类
    [C#][DevPress]手动添加控件中的子控件或者结构
    [C#]XML操作类
    [C#]把DataTable转换成泛型实体List
  • 原文地址:https://www.cnblogs.com/wangxiaobei2019/p/12523843.html
Copyright © 2011-2022 走看看