如何封装Python代码,让别人方便调用,同时又能起到加密的作用,本文介绍如何封装成so文件和dll文件以及调用方式
import datetime
class DataCenter():
def gettime(self):
print(datetime.datetime.now())
def write_data(self):
print("hello XiaoBei!")
from mytest import DataCenter
data = DataCenter()
data.gettime()
data.write_data()
from distutils.core import setup
from Cython.Build import cythonize
#[]内是要打包的文件名,也可多个文件
setup(ext_modules = cythonize(["mytest.py"]))
在当前目录下生成build文件夹和mytest.c文件,.so文件就在build文件夹内
pyd就是dll
# !/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()
# !/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()