SoFunction
Updated on 2025-04-04

How to implement a CLI command line function in Python

In modern software development, the design and interaction of command line interfaces (CLIs) are crucial. Click is a powerful Python library designed to quickly create command line interfaces, winning developers' favor for its simplicity and rich functionality. This article will introduce in detail the functions of the Click library and the application scenarios of the CLI, and show how to implement the CLI through specific code examples.

1. Introduction to Click library functions

Click is a Python library developed by Armin Ronacher to simplify the development process of command line applications. It provides advanced features such as decorators and command groups, allowing developers to easily organize and manage parts of command line applications. Click’s design philosophy is simple, easy to understand and use while meeting complex needs.

Decorators: Click provides decorators such as @() and @() to define commands and options.

Command Group: The @() decorator allows you to create a command group containing multiple subcommands.

Automatically generate help documents: Click can automatically generate help documents for command line applications to improve user experience.

2. Application scenarios of CLI

CLI has a wide range of application scenarios in software development, including but not limited to:

System Management Tools: Through the CLI, developers can create efficient system management tools for monitoring, configuring and managing system resources.

Automated scripts: CLI is the basis for building automated scripts. Through command line parameters and options, you can flexibly control the behavior of scripts.

Data Processing and Analysis Tools: CLI tools can be used for data processing and analysis, receiving input data through the command line and outputting results.

Development Tools and Frameworks: Many development tools and frameworks provide CLI interfaces for project creation, construction, testing, and deployment.

3. Simple use

Here is a sample code for creating a CLI using the Click library, including the ability to display greeting information and calculate the sum of two numbers.

3.1 Installing the Click library

First, make sure you have the Click library installed. If not installed, you can use the following command to install:

pip install click

3.2 Writing CLI applications

Below is a simple CLI application example, including main functions, greeting information commands, and calculation commands.

import click

# Define the main function of the command line interface@()
def cli():
    pass

# Define a command to display greeting information@()
@('name')
def greet(name):
    """Show greeting message"""
    (f'Hello, {name}!')

# Define a command to calculate the sum of two numbers@()
@('x', type=float)
@('y', type=float)
def add(x, y):
    """Count the sum of two numbers"""
    (f'The sum of {x} and {y} is {x + y}')

# Run the command line interfaceif __name__ == '__main__':
    cli()

3.3 Code Description

Import the Click library: Import the Click library through import click.

Define the main function: Use the @() decorator to create a Click group command cli, which can contain multiple subcommands.

Define greeting information command: Use the @() decorator to register the greet function as a subcommand of the cli group. The @('name') decorator means that this command requires a positional parameter name.

Define calculation command: Similarly, the add command is also registered with the @() decorator and accepts two positional parameters x and y, which are specified as floating point type.

Run the command line interface: Call cli() in the main program of the script to start the command line interface.

3.4 Running example

Save the above code as cli_app.py and run the following command in the command line:

python cli_app.py greet Alice

Output:

Hello, Alice!

Run again:

python cli_app.py add 3.5 7.2

Output:

The sum of 3.5 and 7.2 is 10.7

With the above example, we created a simple Click command line application. You can extend this example as needed to add more commands and options.

6. Implement the chat command line function of a large language model

6.1 The hypothetical LanguageModel class

First, we define a simplified LanguageModel class to simulate interaction with large language models. This class will contain a response method that receives user input and returns the model's response.

class LanguageModel:
    def __init__(self):
        # Initialize the model (in actual application, this may be loading a pretrained model or establishing an API connection)        pass

    def respond(self, prompt):
        """
         Simulate the model's response to input.
         In practical applications, the API of the large language model will be called or the local model will be run to get the response.
         """
        # Simple simulation response, here just invert the input as the response (for example only)        return prompt[::-1]  # Note: This is just a very simplified simulation!

6.2 Update the CLI application to include dialogue functionality

Next, we will update the previous CLI application and add a new command to start a conversation with the large language model.

import click

# The hypothetical LanguageModel class (in actual application, it needs to be replaced with real model calling code)class LanguageModel:
    # ... (Same as above)
# Define the main function of the command line interface@()
def cli():
    pass

# ... (The previous greet and add commands can be kept unchanged from here)
# Define a command to start a conversation with a large language model@()
def chat():
    """Conversation with a large language model"""
    model = LanguageModel()  # Initialize the model    print("Start conversation with the big language model. Enter 'exit' to exit.")
    
    while True:
        # Get user input        user_input = input("you: ")
        
        # Check whether you want to exit the conversation        if user_input.lower() == 'exit':
            print("The dialogue ends.")
            break
        
        # Get the model's response        model_response = (user_input)
        
        # Show the model's response        print(f"Model: {model_response}")

# Run the command line interfaceif __name__ == '__main__':
    cli()

6.3 Code Description

LanguageModel class: This is a simplified simulation class for simulating interactions with large language models. In practical applications, you need to replace it with code that calls the real large language model API.

chat command: This command uses an infinite loop to talk to the user until the user enters 'exit'. In each loop, it receives the user's input, calls the LanguageModel's response method to get the model's response, and displays it to the user.

User interaction: Users can interact with the model through the command line, enter text and receive the model's response. Enter 'exit' to end the conversation.

6.4 Running example

Save the above code as cli_app_with_chat.py and then run the following command on the command line to start the CLI application:

python cli_app_with_chat.py chat

Output example (super the simulated LanguageModel just inverts the input, the response will be an inverted string of the input):

Start talking to the big language model. Type 'exit' to exit the conversation.
You: Hello!
Model: ! OK you
You: What's the weather today?
Model: ? How is the weather like today
You: exit
The conversation ends.

Note that since this is a simulation example, the response of the model is very simple and does not conform to the output of the actual large language model. In practice, you need to replace the LanguageModel class with code that can call the real large language model API and process the API's response to generate meaningful conversations.

7. Conclusion

Click is a powerful and flexible command line interface development tool that simplifies the development process of command line applications while providing rich functions and flexible expansion mechanisms. Through the introduction of this article, I believe you have a preliminary understanding of the Click library and have begun to try to use it to build your own command line tools.

This is the end of this article about how Python implements a CLI command line function. For more related Python CLI command line content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!