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

如何为包含多类的Python包创建统一命令行入口点

如何为包含多类的Python包创建统一命令行入口点

First of all, I cannot share the original code so I apologize in advance if the example used does not make sense.
I also know the code I present has some issues and will not run as it is, but it is just to represent an example.

I have created a package with multiple classes. Let's say Circle(radius: float) and Rectangle(side_1: float, side_2: float). And for each one of them, I've created a command line interface entry point, each one corresponding to their correct parameters:

import argparse

def cli_circle():
    parser = argparse.ArgumentParser()
    parser.add_argument("radius")
    args = parser.parse_args()

    Circle(args.radius).calculate_area()

def cli_rect():
    parser = argparse.ArgumentParser()
    parser.add_argument("side_1")
    parser.add_argument("side_2", required=False)
    args = parser.parse_args()

    if args.side_2 is None:
       Rectangle(args.side_1, args.side_1).calculate_area()
    else:
       Rectangle(args.side_1, args.side_2).calculate_area()

I was wondering if it is possible to create a different and common entry point for all the classes. However, I am trying to avoid creating just one class with all the different parameters. My ideal solution would be a function that can call the other two functions, something as following:

def common_cli():
    parser = argparse.ArgumentParser()
    parser.add_argument("--rectangle", help="Runs the Rectangle class")
    parser.add_argument("--circle", help="Runs the Circle class")
    ...
    args = parser.parse_args()
    if args.rectangle:
       cli_rect(args)
    elif args.circle:
       cli_circle(args)
    else:
       raise ValueError("No class was selected.")

Is something like this already existing in Python? Or is my only solution to hardcode this?


备注:内容来源于stack exchange,提问作者Jaime

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 08:49:32