[Python] Create a common CLI entry point in Python

Discussão em 'Python' iniciado por Stack, Fevereiro 3, 2025.

  1. Stack

    Stack Membro Participativo

    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.ArgumetParser()
    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?

    Continue reading...

Compartilhe esta Página