【问题标题】:How to package a Python project to be run in the console如何打包 Python 项目以在控制台中运行
【发布时间】:2021-12-06 20:39:10
【问题描述】:

我用 Python 编写了一个使用多个脚本(模块)的项目。主脚本调用其他模块并从文件夹中读取一些文件以执行其功能。

我正在尝试将其打包以进行分发。我希望从命令行使它成为一个可运行的程序,这意味着一旦用户下载并安装它,他们可以这样调用程序:

$ python my_program -i arg1 -o arg2

或类似的。

我在网上找到的教程以可以导入的包的形式包装项目。

>> import my_program
>> my_program.run_stuff(arg1, arg2)

这不是我想要的。

【问题讨论】:

  • 您可能的意思是您想将其称为my_program -i arg1 -o arg2。他们不应该需要自己的 Python。像pyinstallerpy2exe 这样的工具可以做到这一点。或者,您可以将其打包为一个模块,使用 Python 的人可以输入python -m my_program -i arg1 -o arg2

标签: python packaging python-packaging


【解决方案1】:

既然你写了“或类似的”,假设你想这样调用程序:

$ my_program -i arg1 -o arg2

这甚至更短。这也是我们如何称呼无处不在的 Python 工具,例如 pip。并且有一个既定程序可以为任何 Python 包定义一个“入口点”(众所周知)。

所有 Python 打包工具都允许这样做。如果我们愿意,我们可以use the classic Setuptools — 那是what Pip does。或者use Poetry,一个更现代的选择。但使用Flit 进行设置通常最容易。

在最简单的情况下,您的包my_program 只包含一个定义函数的__init__.py 文件:

def main():
    print('Running my program...')

该函数通常会作用于sys.argv 中的命令行参数。该函数不必调用main,它可以是任何名称,也可以位于包的任何其他模块中。

然后我们可以在项目的元数据中定义控制台脚本的入口点。 Flit 从根文件夹中名为 pyproject.toml 的配置文件中读取它。所以存储库现在看起来像这样:

.
├── my_program
│   └── __init__.py
└── pyproject.toml

使用元数据的最新标准,PEP 621pyproject.toml 将包含:

[project]
name = 'my_program'
version = '1.0.0'
description = 'Can be run in the console from anywhere.'

[project.scripts]
my_program = 'my_program:main'

[build-system]
requires = ['flit_core>=3.2,<4']
build-backend = 'flit_core.buildapi'

[project.scripts] section 中,我们将控制台命令my_program 映射到my_program 包的顶级名称空间中的main 函数。同样,它也可以是包中其他地方的任何其他功能。

现在我们打包项目:

$ flit build --format wheel
Copying package file(s) from my_program              I-flit_core.wheel
Writing metadata files                               I-flit_core.wheel
Writing the record of files                          I-flit_core.wheel
Built wheel: dist\my_program-1.0.0-py2.py3-none-any.whl  I-flit_core.wheel

这会将打包的“轮子”放入名为dist 的文件夹中。我们可以将 .whl 文件上传到 PyPI 进行分发,或者立即使用 Pip 安装它:

$ pip install dist/my_program-1.0.0-py2.py3-none-any.whl
Processing .\dist\my_program-1.0.0-py2.py3-none-any.whl
Installing collected packages: my-program
Successfully installed my-program-1.0.0

现在我们可以像运行任何其他控制台应用程序一样运行该程序:

$ my_program
Running my program...

Pip 为我们所做的是,它在它自己的启动器旁边为我们的包创建了一个小型启动器。就像for Flit 一样。例如,在 Windows 上,Python 的 Scripts 文件夹中现在有一个 my_program.exe,紧邻 pip.exeflit.exe

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 2011-12-23
    • 2015-04-27
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    相关资源
    最近更新 更多