Command-Line Interface for Random Tasks

  • Share this:

Code introduction


This code defines a simple command-line interface with three features: addition, text reversal, and displaying file content.


Technology Stack : Click

Code Type : Command line interface

Code Difficulty : Intermediate


                
                    
import click
import random

@click.group()
def cli():
    """A command line interface for a random task."""
    pass

@cli.command()
@click.argument('number', type=int)
def add(number):
    """Add two numbers together."""
    click.echo(f"The sum of {number} and {number} is {2 * number}")

@cli.command()
@click.argument('text', type=str)
def reverse(text):
    """Reverse the given text."""
    click.echo(text[::-1])

@cli.command()
@click.argument('filename', type=click.Path(exists=True))
def cat(filename):
    """Display the contents of a file."""
    with open(filename, 'r') as file:
        click.echo(file.read())

def main():
    cli()

if __name__ == '__main__':
    main()                
              
Tags: