Random Quote Generator with Length Option

  • Share this:

Code introduction


This code defines a command-line tool using the Click library to generate and display a random quote. Users can specify the length of the quote via command-line arguments.


Technology Stack : Click

Code Type : Command line tool

Code Difficulty : Intermediate


                
                    
import click

def generate_random_quote():
    quotes = [
        "The only way to do great work is to love what you do.",
        "Success is not final, failure is not fatal: It is the courage to continue that counts.",
        "The future belongs to those who believe in the beauty of their dreams.",
        "Don't watch the clock; do what it does. Keep going."
    ]
    import random
    selected_quote = random.choice(quotes)
    return selected_quote

@click.command()
@click.option('--length', type=int, default=10, help='Length of the quote to generate')
def main(length):
    """Generate a random quote of a specified length."""
    quote = generate_random_quote()
    if len(quote) <= length:
        click.echo(quote)
    else:
        click.echo(quote[:length])

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