You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含__main__的CLI脚本配置为setuptools的entry points

配置setuptools entry points实现CLI命令

第一步:重构file1.py代码

把原来写在if __name__ == '__main__':里的CLI逻辑封装成独立函数(比如main()),这样setuptools才能正常调用它。修改后的file1.py示例:

import argparse

def detect():
    # 原detect函数的业务代码
    ...

def main():
    parser = argparse.ArgumentParser()
    # 原argparse参数配置代码
    ...
    opt = parser.parse_args()
    # 后续执行逻辑,比如调用detect()
    detect()

if __name__ == '__main__':
    main()

第二步:修改setup.py配置entry points

在setup.py中添加entry_points参数,通过console_scripts把自定义命令和对应函数关联起来。示例setup.py内容:

from setuptools import setup

setup(
    name="mycli_project",  # 自定义项目名称
    version="0.1",
    py_modules=["file1"],
    entry_points={
        "console_scripts": [
            "mydetect = file1:main",  # mydetect是你要在命令行使用的命令,指向file1里的main函数
        ]
    }
)

第三步:安装项目

在项目根目录执行安装命令,推荐用开发模式安装方便后续调试:

pip install -e .

或者直接完成安装:

python setup.py install

安装完成后,你就可以在命令行直接输入mydetect来运行原CLI逻辑,无需再输入python file1.py。

内容的提问来源于stack exchange,提问作者ccd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 14:49:52