既然你写了“或类似的”,假设你想这样调用程序:
$ 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 621、pyproject.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.exe 和 flit.exe。