Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How Can I Make One Python File Run Another File?
Next article icon

Click Module in Python | Making awesome Command Line Utilities

Last Updated : 14 Mar, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

Since the dawn of the computer age and before the internet outburst, programmers have been using command line tools in an interactive shell as a means to communicate with the computers. It is kind of strange that with all the advancements in UI/UX technologies, very few people know that there are to create beautiful command line interfaces too.
Ever wanted to create a command line tool yourself that is actually very user-friendly, efficient and easy to use? Well, click is a Python Package that does just that. There are many Python packages that we could use instead of click such as argparse, docopt, etc., so we will first look at why we are using click.

Why Click?

There are a couple of reasons why click is the better tool for the job.

  • Click is lazily composable without restrictions.
  • It is fully nested.
  • Click has strong information available for all parameters and commands so that it can generate unified help pages for the full CLI and to assist the user in converting the input data as necessary.
  • Click has a strong understanding of what types are and can give the user consistent error messages if something goes wrong.

Installation:

pip install click

Basics of a Command Line Interface:

Depending on the type and purpose of the CLI, it can have a variety of functionalities. You probably would already have used pip which is also a CLI. Some basics functions which all CLIs have are:

  • An argument.
  • An option, which is an optional parameter
  • A flag, this is a special option which enables or disables a certain function. One of the most common flags is –help.

Simple program using click :




# importing click
import click
  
@click.command()
def main():
    click.echo("This cli is built with click. ")
  
if __name__=="__main__":
    main()
 
 

So let’s build a command line tool that will print a greeting for the name provided in the arguments.

Argument Parsing: Click uses the python decorators for parsing arguments related to a function.




@click.command()
@click.argument('name')
def greeting(name):
    click.echo("Hello, {}".format(name))
  
if __name__=="__main__":
    greeting()
 
 

>>> python greet.py Gifoyle

Hello, Gilfoyle

 
Optional arguments: Click gives the option to include optional parameters in the form of flags.




import click
  
@click.command()
@click.option('--string', default ='World',
        help ='This is a greeting')
def hello(string):
    click.echo("Hello, {}".format(string))
  
if __name__=="__main__":
hello()    
 
 

>>> python hello.py

Hello, World

>>> python hello.py --string Dinesh

Hello, Dinesh

 
Help: The most important and final step towards making the perfect CLI is to provide documentation to our code. Click provides a nice and formatted help text in the command line when used the optional argument --help. It uses the docstring specified in the function.




import click
  
@click.command()
@click.argument(‘greeting’)
def cli(greeting):
    '''
    This is the default CLI method.
      
    Arguments:
            greeting: {string}
    '''
  
    click.echo(greeting)
    click.echo ("This is a simple cli.")
  
if __name__=="__main":
    cli()
 
 

>>> python cli.py --help
This is the default CLI method.

      Arguments:  greeting: {string}    Options:    --string TEXT  Hello    --help         Show this message and exit.  >>>

 
Error Handling: Error handling is an important part of a CLI. How your script handles and manages the errors matters a lot and also helps the user to better understand the mistake.

>>> python cli.py
This is a simple cli.

>>> python cli.py hello

Usage: greet.py [OPTIONS]  Try "greet.py --help" for help.    Error: Got unexpected extra argument (hello)


Next Article
How Can I Make One Python File Run Another File?

A

abhishektiwari3507
Improve
Article Tags :
  • Project
  • Python
  • Python Programs
Practice Tags :
  • python

Similar Reads

  • How Can I Make One Python File Run Another File?
    In Python programming, there often arises the need to execute one Python file from within another. This could be for modularity, reusability, or simply for the sake of organization. In this article, we will explore different approaches to achieve this task, each with its advantages and use cases. Ma
    2 min read
  • Command Line File Downloader in Python
    Python is one of the most popular general-purpose programming languages with a wide range of use cases from general coding to complex fields like AI. One of the reasons for such popularity of python as a programming language is the availability of many built-in as well as third-party libraries and p
    4 min read
  • How Use Linux Command In Python Using System.Os
    Using the system module from the os library in Python allows you to interact with the Linux command line directly from your Python script. This module provides a way to execute system commands, enabling you to automate various tasks by integrating Linux commands seamlessly into your Python code. Whe
    3 min read
  • How to Build a Password Manager in Python
    We have a task to create a Password Manager in Python. In this article, we will see how to create a Password Manager in Python. What is a Password Manager?A Password Manager in Python is a tool in which we can add the username and password. Additionally, it allows us to retrieve the username and pas
    7 min read
  • Installing and Using Rich Package in Python
    In this article, We are going to learn how to install and use rich packages in Python. RIch is a python package for creating some awesome terminal formatting and logging. It has several features and functions that can make your application look nicer and even add a new look to your CLI application.
    10 min read
  • Install Poetry to Manage Python Dependencies
    Poetry is a modern and user-friendly dependency management tool for Python. It simplifies the process of managing project dependencies, packaging, and publishing. In this article, we will see how to install poetry in Python in Windows. What is Python Poetry?Python Poetry is a modern and comprehensiv
    2 min read
  • Python for Kids - Fun Tutorial to Learn Python Programming
    Python for Kids - Python is an easy-to-understand and good-to-start programming language. In this Python tutorial for kids or beginners, you will learn Python and know why it is a perfect fit for kids to start. Whether the child is interested in building simple games, creating art, or solving puzzle
    15+ min read
  • Disappearing Text Desktop Application in Python
    In this article, we will build an exciting desktop application using Python and its GUI library, Tkinter. Disappearing Text Desktop Application in PythonThe app is simple to use. The user will start writing whatever he wants to write. If he takes a pause for 5 seconds, the text he has written is del
    12 min read
  • Python Tutorial | Learn Python Programming Language
    Python Tutorial – Python is one of the most popular programming languages. It’s simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
    10 min read
  • Competitive Coding Setup for C++ and Python in VS Code using Python Script
    Most of us struggle with using heavy software to run C++ and python code and things become more complicated when we have too many files in a folder. In this blog, we are going to create a python script with VS-code-editor that works out to do all your works. It creates the folder + numbers of files
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences