python 程序的打包与安装
本文最后更新于 464 天前,如遇到任何问题欢迎在评论区留言呀!

为了将 Python 程序分发和安装在计算机中,我们需要对已经完成的项目进行打包,打包完成后,可进行安装。

打包

包的种类

Python 的包分为两种,Built Distribution 和 Source Distribution(简称 sdist)。

简单来讲,不同操作系统安装 Python 包的要求不完全相同,Built Distribution 是按照某类操作系统(例如 Linux)安装要求所打成的包,这样安装的时候只需要将包解压,文件放到适当的位置即可,效率比较高。但一个 Built Distribution 只适用于一类操作系统,例如 Linux 上的 Built Distribution 包无法在 Windows 上安装。而 Source Distribution 包便解决了这个问题,它是对源代码进行打包,将源代码打包成利于打成 Built Distribution 包的形式。这样,我们便可以通过 Source Distribution 包生成适用于特定类型操作系统的 Built Distribution 包,再进行安装。

Built Distribution

A Distribution format containing files and metadata that only need to be moved to the correct location on the target system, to be installed. Wheel is such a format, whereas distutil’s Source Distribution is not, in that it requires a build step before it can be installed. This format does not imply that Python files have to be precompiled (Wheel intentionally does not include compiled Python files).

Source Distribution (or “sdist”)

A distribution format (usually generated using python setup.py sdist) that provides metadata and the essential source files needed for installing by a tool like pip, or for generating a Built Distribution.

如何打包

打包前的准备

打包前需要在项目根目录下创建两个文件,pyproject.tomlsetup.cfg

pyproject.toml

[build-system]
requires = [
    "setuptools>=42",
    "wheel"
]
build-backend = "setuptools.build_meta"

setup.cfg

这个文件不能直接复制,具体怎么写可看参考资料 1 的内容。

[metadata]
name = package_name
version = 0.0.1
author = author_name
description = ...

[options]
packages = find:
python_requires = >=3.6
install_requires =
    ping3
    tabulate

[options.entry_points]
console_scripts =
    command_name = src.__main__:main

进行打包

后续打包操作适用于 Unix-like 系统,如果是 Windows 系统请参考资料 1。

安装打包工具build

python3 -m pip install --upgrade build

在项目的根目录下进行打包:

python3 -m build

打包完成后,便可发现项目的根目录下多了一个dist目录:

dist/
  filename.whl
  filename.tar.gz

其中,*.whl文件是 Built Distribution 包,*.tar.gz是 Source Archive(源代码归档),可用于后续生成 Source Distribution 和 Built Distribution 包。

安装

上一步得到的.whl包可以直接安装:

pip install *.whl

不过如果仅仅是为了安装在自己的计算机上,可以先移动到项目根目录下,然后直接安装:

pip install .

这样,由安装程序自动进行打包,无需手动打包。

参考资料

  1. Packaging Python Projects
  2. Python Packaging User Guide Glossary
  3. How do I install a Python package with a .whl file?
  4. 编写 setup.py 打包 python 程序且安装到命令行运行
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇