<!DOCTYPE html>
python打包有一个组织叫python packaging authority(pypa).还有一个python第三方仓库叫Python Package Index(Pypi)
与包有关的两种工具,一种是安装包的工具,另外一种工具用于包的建立和分发
html
建立大型的应用最简单的作法是分几个包,这样就像分红各个组件,这样易于理解维护和修改。
python
from setuptools import setup
setup(
name='wjtestpack'
)
setup中name的参数为要打包的全名,setup脚本可使用一些命令,使用以下命令查看 git
python3 setup.py --help-commands
#输出结果
Standard commands:#标准命令 是distutils的内置命令
build build everything needed to install
build_py "build" pure Python modules (copy to build directory)
build_ext build C/C++ extensions (compile/link to build directory)
build_clib build C/C++ libraries used by Python extensions
build_scripts "build" scripts (copy and fixup #! line)
clean clean up temporary files from 'build' command
install install everything from build directory
install_lib install all Python modules (extensions and pure Python)
install_headers install C/C++ header files
install_scripts install scripts (Python or otherwise)
install_data install data files
sdist create a source distribution (tarball, zip file, etc.)
register register the distribution with the Python package index
bdist create a built (binary) distribution
bdist_dumb create a "dumb" built distribution
bdist_rpm create an RPM distribution
bdist_wininst create an executable installer for MS Windows
check perform some checks on the package
upload upload binary package to PyPI
Extra commands:setuptools包中定义的命令
bdist_wheel create a wheel distribution
alias define a shortcut to invoke one or more commands
bdist_egg create an "egg" distribution
develop install package in 'development mode'
easy_install Find/get/install Python packages
egg_info create a distribution's .egg-info directory
install_egg_info Install an .egg-info directory for the package
rotate delete older distributions, keeping N newest files
saveopts save supplied options to setup.cfg or other config file
setopt set an option in setup.cfg or another config file
test run unit tests after in-place build
upload_docs Upload documentation to PyPI
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
setup.cfg文件就是包含setup脚本命令的默认参数数据。若是建立包的过程复杂,须要像setup脚本传入参数不少,使用这个文件就简单不少。能够讲项目的默认参数保存在这个文件中。也将包的构建过程透明化。
cfg文件与configparser语法相同,都是一个个节点与值对应 程序员
[global]
quiet=1
[sdist]
formats=zip,tar
[bdist_wheel]
universal=1
以上配置描述的是,发行包建立格式为zip和tar两种格式的文件,而且构建wheel打包,全局命令quiet为1,因此命令的大部分输出被阻止。 github
mainifest文件就是一个包含发行包的全部文件的信息的文件,使用sdist命令构建包的时候,distutils会自动浏览应用中的全部文件,生成列表,保存在manifest文件中 web
除了须要的包名和版本以外,setup函数能够接受不少参数
* description:描述包的信息 * longdescription:完整包的说明,可使用reStructuredText格式
* keywords:包中关键字列表
* author:做者的名称
* authoremail:做者邮箱
* url:项目URL * license:许可证
* packages:包中全部名称的列表,setuptools有一个findpackages的函数计算
* namespacepackages:命令空间包的列表 编程
分类器的主要做用是对你建立的包在pypi中有一个所属类的定位,分类器都是字符串形式,用::字符串分割每一个命名空间。分类器列表在包的setup()函数中定义用的参数为classifiers,举个例子 canvas
from setuptools import setup
setup(
name='mytestpack'
classifiers=[
'Development Status:: 4-Beta',
'Intended Audience::Developers',
'License::OSI...',
'Operating System::OS',....
] )
pypi分类器一共有9大类
* 开发状态(Development Status) * 环境(Environment) * 框架(Framework) * 目标受众(Intended Audience) * 许可证(License) * 天然语言(Natural Language) * 操做系统(Operating System) * 编程语言(Programming Language) * 话题(Topic) windows
其实打包信息能够在setup函数中接受大多数元数据的手动输入,代码以下
from setuptools import setup
setup(
name='mytestpack'
version='0.0.1',
description='test package',
long_description='wj first use setuptools',
install_requires=[
'dependency1',
'dependenct2',
]
)
可是setuptools和distutils都不能从项目源代码中自动提取元数据信息,须要你本身提供这些信息。长远来看上面的方法很难维护。因此python社区有一些方法来解决这些问题:
(1) 自动添加包的版本字符串
这个操做须要将包的版本信息编写进包的init.py文件中,因此之后建立包的init.py文件须要包含以下格式的信息
VERSION=(0,1,1) __version__='.'.join([str(x) for x in VERSION])
版本信息包含在VERSION和version中,这样访问这两个变量就能够获取版本号,因此在setup.py脚本中动态获取版本号代码以下
from setuptools import setup
import os
def get_version(version_tuple):
if not isinstance(version_tuple[-1],int):
return '.'.join(map(str,version_tuple[:-1]))+version_tuple[-1]
return '.'.join(map(str,version_tuple))
init=os.path.join(os.path.dirname(__file__),'下一层文件夹命',...,'__init__.py')
version_line=list(
filter(lambda l:l.startswith("VERSION"),open(init))
)[0]
VERSION=get_version(eval(version_line.split('=')[-1]))
setup(
name='mytestpack',
version=VERSION,
)
(2)使用README文件
python包在pypi中会显示一个项目的readme文件,pypi只支持reStructuredText标记语言。固然若是想使用其余语言,那就只能读取文件,而后将数据赋值到long_description中,这样也能够显示。这时须要使用pypandoc包将其余语言转换为reStructuredText
try:
from pypandoc import convert
def read_md(f):
return convert(f,'rst')
except ImportError:
covert=None
print('warning:pypandoc not found')
README=os.path.join(os.path.dirname(__file__),'README.md')
setup(
name='mytestpack',
long_description=read_md(README),
)
(3)管理依赖
有些应用包的须要依赖其余包,这就要咱们列出一个依赖列表,以下是一个明确表述依赖列表的形式:
from setuptools import setup
setup(
name='mytestpack',
install_requires=['pack1','pack2','pack3'],
)
也可使用读取requirements.txt文件的形式
from setuptools import setup
import os
def strip_comments(l):
reeturn l.split('#',1)[0].strip()
def reqs(*f):
return list(filter(None,[strip_comments(l) for l in open(os.path.join(os.getcwd(),*f)).readlines()]))
setup(
name='mytestpack',
install_requires=reqs('requirements.txt')
)
distutils提供了自定义命令的入口点(entry point),只要在setup函数里使用entry_point参数就能够注册命令,这样的形式和crf文件格式相似
setup(
name='mytestpack',
entry_point="""
[distutils.commands]
my_command=my.command.module.Class
""",
)
开发期间使用包就是为了测试包是否能正藏安装
1.安装
使用pip命令就能够将安装包注册到python树中,由于个人电脑里有两个版本的python,因此python的pip命令以下
python3 -m pip install C:\Users\Mr.Bool\Desktop\testproject\testp
2.卸载
python3 -m pip uninstall C:\Users\Mr.Bool\Desktop\testproject\testp
在系统包上卸载包是很危险的可能会卸掉某些重要文件,这也证实虚拟环境对于开发的重要性 3.开发模式下安装
python3 -m pip install -e C:\Users\Mr.Bool\Desktop\testproject\testp
命名空间有两种,一种是上下问的命名空间,即保存变量的字典称为命名空间,有模块的全局命名空间,函数方法的本地命名空间,内置名称的命名空间
1. 内置命名空间在 Python 解释器启动时建立,会一直保留,不被删除。
2. 模块的全局命名空间在模块定义被读入时建立,一般模块命名空间也会一直保存到解释器退出。
3. 当函数被调用时建立一个局部命名空间,当函数返回结果 或 抛出异常时,被删除。每个递归调用的函数都拥有本身的命名空间。
还有另一种命名空间,叫作命名空间包,这是在项目中对于打包的时候用的一种功能。
当你在开发应用是一般是多个组件,举个例子是当你的一个大的应用a中,包含b,c两个模块,而b和c是单独存在的两个模块,你能够单独使用,在没有命名空间包的状况下这是不可能的状况,由于b和c都在a的下面,要下载就只能都下载,出现了命名空间包,那么将a变成命名空间包,那么就在python的层面上将b,c能够单独使用和修改。但两个包又能够同时存在a的下面。
pip install a.b
pip install a.c
而没有命名空间包的时候你要下载通用包
pip install a
隐式命名空间包意思就是只要在你写的应用中,不包含init.py的包就做为命名空间包,setup.py脚本中这样写:
from setuptools import setup
setup(
name='a.b',
packages=['a.b'],
)
古老的方法在a中是有文件init.py文件的,但必须是空白,但最好添加一段代码
__import__('pkg_resources').declare_namespace(__name__)
在setup文件中这样声明
from setuptools import setup
setup(
name='a.b',
packages=['a.b],
namespace_packages=['a'],#主动声明命名空间包
)
从pypi上下载python包不须要帐号,只须要一个包管理器。首选是pip
任何人均可以上传python包,只须要注册仓库的帐户密码,包与帐户绑定。上传一个包的简单方法使用setup.py的命令upload
python setup.py 命令列表 upload
若是你想同事构建源代码发行版、构建发行版和wheel包,使用以下命令
python setup.py sdist bdist bdist_wheel upload
由于这样做不安全,最好使用twine工具,能够在pypi平台下载,
pytho setup.py sdist bdist_wheel twine upload dist/*
若是这个包没有注册上传会失败,先注册
python register dist/*
.pypirc是一个配置文件,保存python包仓库的信息
[distutils]
index-servers=pypi other #注册的仓库
[pypi]
repository:<仓库url>
username:用户名
password:密码
[other]
repository:<仓库url>
username:用户名
password:密码
用户名密码能够空着,安全,必要时程序会提示输入
1.sdist
sdist命令建立源代码发行版
python setup.py sdist
生成的文件形式为举例:mypackage-0.1.1.tar.gz的打包文件包含与项目相同的结构
2.bdist和wheels
分发预构建的发行版
python setup.py bdist
会生成文件形式为wjtestpack-0.0.0.win-amd64.zip格式的压缩包,这个包里主要有site-packages的文件夹,和一些缓存字节码.pyc结尾的文件。
使用wheels命令以下
python setup.py bdist_wheel
生成的文件为wjtestpack-0.0.0-py3-none-any.whl形式的文件。
建立独立可执行文件是每种语言必须实现的,由于不会全部使用者都是程序员,也不会全部使用应用的电脑都有特定语言的解释环境。
能够应用到多平台,不支持跨平台构建,使用pyinstaller首先须要用pip安装pyinstaller,使用pyinstaller建立独立可执行文件的命令以下
pyinstaller 路径/mytest.py
这样运行会生成一个.spec文件和一个dist文件夹,文件夹中包含,许多文件,其中有一个exe可执行文件,当将应用发给用户时必须将整个文件夹发给用户。也可使用以下命令
pyinstaller --onefile mytest.py
使用--onefile构建能够去掉全部多余文件,在一会有.spec文件和dist文件夹下一个.exe可执行文件。
.spec是一个配置文件,其实使用配置文件也能够生成可执行文件,命令以下,前提必须现有.spec文件,能够本身编写
pyinstaller mytest.spec
也是可应用到多平台,不支持跨平台构建,这个工具的缺点为不能只生成可执行文件,它必须生成多个dll等关联文件。生成可执行文件命令为
cxfreeze mytest.py
cxfreeze扩展了distutils包,能够直接使用setup.py文件配置构建生成可执行文件,setup.py代码以下
import sys
from cx_Freeze import setup,Executable
setup(
name='mytest',
version='0.0.1',
description='使用cxfreeze',
options={
'build_exe':build_exe_options
},
executables=[Executable('mytest.py')]
)
执行命令为
python setup.py build_exe
py2exe为生成windows程序的工具,py2app为生成mac程序的工具,两个工具优先级比前两个低,若是前两个很差用,再用这两个