Command-Line Tool with Greet, Read File, and Add Commands

  • Share this:

Code introduction


This code defines a simple command-line tool that includes three commands: greet, read_file, and add. The greet command is used to greet the user and display their age, the read_file command is used to read and print the contents of a file, and the add command is used to add one to a number.


Technology Stack : Click

Code Type : Command line tool

Code Difficulty : Intermediate


                
                    
import click
import random

@click.group()
def cli():
    pass

@cli.command()
@click.argument('name')
@click.argument('age', type=int)
def greet(name, age):
    """Greet someone by their name and age."""
    click.echo(f"Hello, {name}! You are {age} years old.")

@cli.command()
@click.argument('file_path')
def read_file(file_path):
    """Read and print the contents of a file."""
    with open(file_path, 'r') as file:
        content = file.read()
        click.echo(content)

@cli.command()
@click.argument('number', type=int)
def add(number):
    """Add two numbers together."""
    click.echo(number + 1)

def main():
    cli()                
              
Tags: