如何在setup.py中使用entry_points定义命令行工具?请给出一个完整示例。
from setuptools import setup
setup(
name="my_tool",
version="0.1",
packages=["my_tool"],
entry_points={
"console_scripts": [
"my_command = my_tool.main:main",
],
},
)
在 setup.py 中使用 entry_points 字段可以定义命令行工具。具体实现步骤如下:
-
首先,确保项目中存在一个模块(例如
my_tool),并且在模块中包含一个具体的函数(例如main)作为命令行工具的入口点。 -
在
setup.py文件中,通过setup()函数定义项目的元信息,其中entry_points字段用于注册命令行工具。entry_points是一个字典,其中的console_scripts键用于指定命令行工具的入口点。 -
console_scripts是一个列表,每个元素是一个字符串,格式为"命令名 = 模块路径:函数名"。例如,"my_command = my_tool.main:main"表示命令行工具的名称是my_command,调用的函数是my_tool.main模块中的main函数。
完整示例步骤如下:
项目结构
my_project/
├── my_tool/
│ ├── __init__.py
│ └── main.py
└── setup.py
my_tool/main.py 文件内容
def main():
print("Hello from my_command!")
setup.py 文件内容
from setuptools import setup
setup(
name="my_tool",
version="0.1",
packages=["my_tool"],
entry_points={
"console_scripts": [
"my_command = my_tool.main:main",
],
},
)
安装并测试
- 在项目根目录下运行以下命令安装项目:
pip install -e .
- 安装完成后,可以直接在终端中使用
my_command命令:
my_command
- 输出结果为:
Hello from my_command!
注意事项
entry_points中的路径必须指向项目中真实的模块和函数,否则安装时会报错。- 通过
pip install -e .安装时,会以“开发模式”安装,方便调试。 - 如果需要发布到 PyPI,可以通过
python setup.py sdist bdist_wheel打包,然后通过twine upload dist/*上传。
通过这种方式,可以将 Python 脚本快速封装为命令行工具,方便用户直接调用。