如何在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 字段可以定义命令行工具。具体实现步骤如下:

  1. 首先,确保项目中存在一个模块(例如 my_tool),并且在模块中包含一个具体的函数(例如 main)作为命令行工具的入口点。

  2. 在 setup.py 文件中,通过 setup() 函数定义项目的元信息,其中 entry_points 字段用于注册命令行工具。entry_points 是一个字典,其中的 console_scripts 键用于指定命令行工具的入口点。

  3. 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",
        ],
    },
)

安装并测试

  1. 在项目根目录下运行以下命令安装项目:
pip install -e .
  1. 安装完成后,可以直接在终端中使用 my_command 命令:
my_command
  1. 输出结果为:
Hello from my_command!

注意事项

  • entry_points 中的路径必须指向项目中真实的模块和函数,否则安装时会报错。
  • 通过 pip install -e . 安装时,会以“开发模式”安装,方便调试。
  • 如果需要发布到 PyPI,可以通过 python setup.py sdist bdist_wheel 打包,然后通过 twine upload dist/* 上传。

通过这种方式,可以将 Python 脚本快速封装为命令行工具,方便用户直接调用。