传统的python打包工具(例如wheel),是将python代码打入一个压缩包(例如.tar.gz),并改名为.whl。安装时解包,然后源码会放在site-package下面,这样对于某些需要python代码保密的场合不适用。.
当遇到源码需要保密的场合,可以考虑通过.pyc代替.py来提供服务。
下面的简单的步骤说明:
- 生成.pyc
使用py_compile来生成pyc文件。假如import 生成的pyc文件失败,则将文件名改为模块名。然后删除所有的py文件
参考资料:https://zhuanlan.zhihu.com/p/344040942 - 在项目根目录同级的目录创建一个setup.py,内容包括
from setuptools import setup,find_packages
import sys
import compileall
# Compile all the .py files under my_proj/m1.
# The pyc files get created in the same directory alongside the py file
compileall.compile_dir('dir')
# Not including the m1 directory in the packages, but including pyc patterns in
# package_data
setup(
name='my-pyapp',
version='0.0.1',
packages=find_packages(),
package_data={
'': ['dir/*.pyc'],
},
)
这里通过package_data来引入.pyc
参考资料:https://gist.github.com/raghavan97/9e1e6fadc838978666fd47a08c90ba95
3. 执行
pip install wheel
python setup.py bdist_wheel
来创建wheel包。
注意可以通过在与setup.py 同级的目录下创建一个MANIFEST.in,在文件内可以设置项目需要包含的非.py文件,规则如下:
目前遇到的问题:.pyc导入后,可以实现import,但是import完的对象的方法无法访问,报错信息如下:
AttributeError: module 'xxx' has no attribute x'