Home > Article > Backend Development > How to use setup.py file in Python?
Usually we are accustomed to using pip to install some third-party modules. The reason why this installation process is simple is because the module developers do it silently for us. All the complicated work is eliminated, and this process is packaging.
Packaging is to further encapsulate your source code and arrange all the deployment work in advance, so that users can install and use it immediately after getting it, without having to worry about how to deploy it (if you don’t want to If you do it manually based on a bunch of deployment documents).
Python has been developed for so many years, and the project packaging tools have also become very mature. What are they?
You may have heard of disutils, distutils, distutils2, setuptools, etc., which seem familiar but unfamiliar at the same time. What is the relationship between them?
distutils is a standard library of Python. From the naming, it is easy to see that it is a distribution tool (utlis). It is a distribution and packaging tool officially developed by Python. All subsequent packaging tools are developed based on it.
The essence of distutils lies in writing setup.py, which is a guidance file for module distribution and installation.
So how to write setup.py? There is a lot of content in it. I will analyze it in detail later. Please read it patiently.
You may not have written setup.py, but you have definitely used setup.py to do something, such as the following command, which we often use to install modules.
$ python setup.py install
Such an installation method is called Source code installation, which corresponds to binary software package installation, which I will also introduce later.
setuptools is an enhanced version of distutils and is not included in the standard library. It extends many functions to help developers better create and distribute Python packages. Most Python users use the more advanced setuptools module.
distribute, maybe you have seen it in other places, so I will mention it here.
distribute means that setuptools has a branch version. The reason for the branch may be that some developers think that setuptools development is too slow. But now, distribute is merged back into setuptools. Therefore, we can consider them to be the same thing.
There is also a large package distribution tool called distutils2, which attempts to make full use of distutils, detuptools and distribute and become a standard tool in the Python standard library. But the plan did not achieve its intended purpose and is an abandoned project.
Therefore, setuptools is an excellent and reliable Python package installation and distribution tool.
When creating a virtual environment through pycharm, the setuptools tool will be installed by default.
After you install setuptools, you will have a third-party management tool called easy_install, which is also a major improvement that distinguishes it from distutils.
Here is a brief introduction to its usage, although it has been used very rarely.
First is the installation of the package
安装 # 通过包名,从PyPI寻找最新版本,自动下载、编译、安装 $ easy_install pkg_name # 通过包名从指定下载页寻找链接来安装或升级包 $ easy_install -f http://pythonpaste.org/package_index.html # 指定线上的包地址安装 $ easy_install http://example.com/path/to/MyPackage-1.2.3.tgz # 从本地的 .egg 文件安装 $ easy_install xxx.egg # 在安装时你可以添加额外的参数 指定安装目录:--install-dir=DIR, -d DIR 指定用户安装:--user 升级 # 从 pypi 中搜索并升级包 $ easy_install --upgrade pkg_name # 指定版本进行升级 $ easy_install "SomePackage==2.0" 删除 $ easy_install -m pkg_name
To summarize: setuptools is an official professional tool for package distribution. From the perspective of installation, its function is indeed simple. Its greater significance is that it is very useful for package distribution. The customization program is very high. We are still using it to release version packages.
The distribution of Python packages can be divided into two types:
Released in the form of source code package
Release as a binary package
The process of installing a package released as a source package is to first decompress, then compile, and finally install (the python mentioned above setup.py install), so it is cross-platform. Since each installation requires compilation, the installation speed is slower than the binary package installation method.
The essence of the source code package is a compressed package. Its common formats are:
Binary package The installation process omits the compilation process and directly decompresses and installs, so the installation speed is faster than the source code package.
Since packages compiled for different platforms cannot be used universally, packages for multiple platforms need to be compiled in advance when publishing.
Common formats of binary packages are:
The Egg format was introduced by setuptools in 2004 , and the Wheel format was defined by PEP427 in 2012. Wheel appeared to replace Egg. Its essence is a zip package, which is now considered the standard format for Python binary packages.
The following are the main differences between Wheel and Egg:
Wheel has an official PEP427 definition, while Egg does not have a PEP definition
Wheel 是一种分发格式,即打包格式。而 Egg 既是一种分发格式,也是一种运行时安装的格式,并且是可以被直接 import
Wheel 文件不会包含 .pyc 文件
Wheel 使用和 PEP376 兼容的 .dist-info 目录,而 Egg 使用 .egg-info 目录
Wheel 有着更丰富的命名规则。
Wheel 是有版本的。每个 Wheel 文件都包含 wheel 规范的版本和打包的实现
Wheel 在内部被 sysconfig path type 管理,因此转向其他格式也更容易
wheel 包可以通过 pip 来安装,只不过需要先安装 wheel 模块,然后再使用 pip 的命令。
$ pip install wheel $ pip wheel --wheel-dir=/local/wheels pkg
打包分发最关键的一步是编写 setup.py 文件。
以下是一个 setup.py 简单的使用示例
from setuptools import setup, find_packages setup( name="mytest", version="1.0", author="name", author_email="name@163.com", # 项目地址 url="https://github.com/test/mytest", description="Learn to Pack Python Module", # 你要安装的包,通过 setuptools.find_packages 自动发现当前目录下有哪些包 packages=find_packages() )
接下来,我将慢慢扩充这个setup函数,增加更多的参数,以便你能理解setup函数能做哪些事情。
有些库并不是在所有的 Python 版本中都适用的,若一个库安装在一个未兼容的 Python 环境中,理论上不应该在使用时才报错,而应该在安装过程就使其失败,提示禁止安装。
这可以使用 python_requires 来实现。
setup( ... python_requires='>=2.7, <=3', )
from setuptools import setup, find_packages setup( ... # 表明当前模块依赖哪些包,若环境中没有,则会从pypi中下载安装 install_requires=['docutils>=0.3'], # setup.py 本身要依赖的包,这通常是为一些setuptools的插件准备的配置 # 这里列出的包,不会自动安装。 setup_requires=['pbr'], # 仅在测试时需要使用的依赖,在正常发布的代码中是没有用的。 # 在执行python setup.py test时,可以自动安装这三个库,确保测试的正常运行。 tests_require=[ 'pytest>=3.3.1', 'pytest-cov>=2.5.1', ], # 用于安装setup_requires或tests_require里的软件包 # 这些信息会写入egg的 metadata 信息中 dependency_links=[ "http://example2.com/p/foobar-1.0.tar.gz", ], # install_requires 在安装模块时会自动安装依赖包 # 而 extras_require 不会,这里仅表示该模块会依赖这些包 # 但是这些包通常不会使用到,只有当你深度使用模块时,才会用到,这里需要你手动安装 extras_require={ 'PDF': ["ReportLab>=1.2", "RXP"], 'reST': ["docutils>=0.3"], } )
from setuptools import setup, find_packages setup( name="mytest", version="1.0", author="name", author_email="name@163.com", description="Learn to Pack Python Module", url="https://github.com/test/mytest", packages=find_packages(), # 安装过程中,需要安装的静态文件,如配置文件、service文件、图片等 data_files= [ ('', ['conf/*.conf']), ('/usr/lib/systemd/system/', ['bin/*.service']), ], # 希望被打包的文件 package_data={ '':['*.txt'], 'bandwidth_reporter':['*.txt'] }, # 不打包某些文件 exclude_package_data={ 'bandwidth_reporter':['*.txt'] } )
classifiers 参数说明包的分类信息。
示例:
from setuptools import setup, find_packages setup( classifiers = [ # 发展时期,常见的如下 # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', # 开发的目标用户 'Intended Audience :: Developers', # 属于什么类型 'Topic :: Software Development :: Build Tools', # 许可证信息 'License :: OSI Approved :: MIT License', # 目标 Python 版本 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ] )
from setuptools import setup, find_packages setup( ... # 用来支持自动生成脚本,安装后会自动生成 /usr/bin/foo 的可执行文件 # 该文件入口指向 foo/main.py 的main 函数 entry_points={ 'console_scripts': [ 'foo = foo.main:main' ] }, # 将 bin/foo.sh 和 bar.py 脚本,生成到系统 PATH中 # 执行 python setup.py install 后会生成 如 /usr/bin/foo.sh 和 如 /usr/bin/bar.py scripts=['bin/foo.sh', 'bar.py'] )
上面的 scripts 里有的脚本中有 sh 和 py 后缀,那么安装后,setuptools 会原封不动的移动到 /usr/bin 中,并添加可执行权限。
setup.py 里只能指定 version,而不能指定 release,如果你需要变更版本号,可以使用 --release 参数进行指定
python setup.py bdist_rpm --release=20200617
setup.py 的参数非常多,能够不借助文档写好一个setup.py好像没那么简单。为了备忘,我整理了 setup 函数常用的一些参数:
a、构建源码发布包。
用于发布一个 Python 模块或项目,将源码打包成 tar.gz (用于 Linux 环境中)或者 zip 压缩包(用于 Windows 环境中)
$ python setup.py sdist
那这种包如何安装呢?
答案是,使用下一节即将介绍的 setuptools 中提供的 easy_install 工具。
$ easy_install xxx.tar.gz
使用 sdist 将根据当前平台创建默认格式的存档。在类 Unix 平台上,将创建后缀后为 .tar.gz 的 gzip 压缩的tar文件分发包,而在Windows上为 ZIP 文件。
当然,你也可以通过指定你要的发布包格式来打破这个默认行为
$ python setup.py sdist --formats=gztar,zip
你可以指定的格式有哪些呢?
创建一个压缩的tarball和一个zip文件。可用格式为:
对以上的格式,有几点需要注意一下:
在版本3.5中才添加了对 xztar 格式的支持
zip 格式需要你事先已安装相应的模块:zip程序或zipfile模块(已成为Python的标准库)
ztar 格式正在弃用,请尽量不要使用
另外,如果您希望归档文件的所有文件归root拥有,可以这样指定
python setup.py sdist --owner=root --group=root
b、构建二进制分发包。
在windows中我们习惯了双击 exe 进行软件的安装,Python 模块的安装也同样支持 打包成 exe 这样的二进制软件包。
$ python setup.py bdist_wininst
而在 Linux 中,大家也习惯了使用 rpm 来安装包,对此你可以使用这条命令实现 rpm 包的构建
$ python setup.py bdist_rpm
若你喜欢使用 easy_install 或者 pip 来安装离线包。你可以将其打包成 egg 包
$ python setup.py bdist_egg
若你的项目,需要安装多个平台下,既有 Windows 也有 Linux,按照上面的方法,多种格式我们要执行多次命令,为了方便,你可以一步到位,执行如下这条命令,即可生成多个格式的进制包
$ python setup.py bdist
正常情况下,我们都是通过以上构建的源码包或者二进制包进行模块的安装。
但在编写 setup.py 的过程中,可能不能一步到位,需要多次调试,这时候如何测试自己写的 setup.py 文件是可用的呢?
这时候你可以使用python setup.py install命令,它会将你的模块安装至系统全局环境中.
如若你的项目还处于开发阶段,频繁的安装模块,也是一个麻烦事。
这时候你可以使用这条命令安装,该方法不会真正的安装包,而是在系统环境中创建一个软链接指向包实际所在目录。这边在修改包之后不用再安装就能生效,便于调试。
$ python setup.py develop
通过上面的学习,你一定已经学会了如何打包自己的项目,若你觉得自己开发的模块非常不错,想要 share 给其他人使用,你可以将其上传到 PyPi (Python Package Index)上,它是 Python 官方维护的第三方包仓库,用于统一存储和管理开发者发布的 Python 包。
如果要发布自己的包,需要先到 pypi 上注册账号。然后创建 ~/.pypirc 文件,此文件中配置 PyPI 访问地址和账号。如的.pypirc文件内容请根据自己的账号来修改。
典型的 .pypirc 文件
[distutils] index-servers = pypi [pypi] username:xxx password:xxx
然后使用这条命令进行信息注册,完成后,你可以在 PyPi 上看到项目信息。
$ python setup.py register
注册完了后,你还要上传源码包,别人才使用下载安装
$ python setup.py upload
The above is the detailed content of How to use setup.py file in Python?. For more information, please follow other related articles on the PHP Chinese website!