DEV Community 👩‍💻👨‍💻

Cover image for How I made the CLI app with Python
Kelvin Wangonya
Kelvin Wangonya

Posted on

How I made the CLI app with Python

Since I began learning Python, I've been amazed by how much you can do with it, and how easy it actually is once you get comfortable with it. I've always loved working on the terminal, so to make my learning a bit fun, I learned how to make cli apps with Click and made a Chuck Norris jokes app late last year:

I posted the app on PyPi and as a Python beginner, you can just imagine my joy on seeing something I did up on PyPi. PyPi! 😄 Awesome feeling.

Then yesterday, I had to take a break from work and decided to open I like to have my browser closed if I don't require it for whatever I'm doing to avoid distractions. So I switched workspaces, opened up my browser, clicked on the bookmark and there I was. The idea just popped into my head: I could bypass all this if I had one command to open from the terminal. I was already on my terminal before anyway so this seemed like a good idea 😄. Of course, this could be done for any website - I just thought of because that's what made me go through the process in the first place.

As usual, the community was very supportive!

This was fun =) You should add a bit about the process, what you needed to make this happen and how to make a package to share.

I'll do that on the next post. Thanks! 😊

So here's how I did it.

In case you want to follow along, now's the time to create a new directory, cd into it, and create your virtual environment.

$ mkdir
$ cd
$ virtualenv venv # pip install virtualenv if you don't have it
$ source venv/bin/activate
(venv) $ mkdir app
(venv) $ touch app/ # this is where we'll write our code
(venv) $ touch requirements.txt # this will hold the project's requirements
Enter fullscreen mode Exit fullscreen mode

click & the webbrowser module

At the heart of this whole thing is these two lines of code:

import click
import webbrowser
Enter fullscreen mode Exit fullscreen mode

webbrowser provides the powers to open the browser, and click makes it a cli app.

webbrowser comes with python so all we need to install is click.

(venv) $ pip install click
(venv) $ pip freeze > requirements.txt # add the installed module to our requirements file
Enter fullscreen mode Exit fullscreen mode

Now that we have what we need, we can go ahead to write the code. Add the following code to app/ I'll explain what each line does.

import click
import webbrowser

@click.option('--tag', '-t', help='add a tag')
def main(tag):
    Open a new browser tab on the browser
    if tag:
        url = '{}'.format(tag)
        url = '', new=2)

if __name__ == "__main__":
Enter fullscreen mode Exit fullscreen mode

It's really that simple! Even a beginner would be able to make sense of what this code does.

This click decorator converts the main() function into a cli command. Without it, it would just be a normal python function. But with it, it becomes command that can be invoked as a command line utility.

@click.option('--tag', '-t', help='add a tag')
@click.option() extends the command to be able to accept extra arguments. In this case, --tag or its shorthand version -t is allowed. The help text explains what the argument does.

def main(tag):
This is our app's entrypoint, where all the magic happens. The function (now a command) takes an optional tag argument, which determines the url to be opened as seen in the if else a few lines below it.

"""Open a new browser tab on the browser"""
comment, new=2)
Opens the requested url. new=2 makes sure this is done in a new tab.

And finally, the if __name__ block runs the main() function when the script runs.

Having the code above, just run the to see it work.

$ python app/
Enter fullscreen mode Exit fullscreen mode

A new tab should automatically open on your browser.

$ python app/ --help
Usage: [OPTIONS]

  Open a new browser tab on the browser

  -t, --tag TEXT  add a tag
  --help          Show this message and exit.
Enter fullscreen mode Exit fullscreen mode

Let's try out passing in a tag.

$ python app/ --tag react
Enter fullscreen mode Exit fullscreen mode should be opened 😀.

We don't want to keep running python app/ everytime though. In the next post, I'll show how to use setuptools to bundle the script so we can install it locally and use the simple command to run the script instead of the long python app/ I'll also show how to publish a package on PyPi.


Top comments (6)

jasper_zanjani profile image
Jasper Zanjani • Edited on

you could probably do this in a very short shell script

if [ $# != 2 ]
  echo "Usage: tag"
  exit 1; 
  firefox "$1"
fronkan profile image
Fredrik Sjöstrand • Edited on

So I came across this and I had to see how short I could make it in Python. This was the shortest I could make it while keeping it nice looking. Here I use start chrome ... as I am running it on a Windows box.

import os
import sys
page = '' if len(sys.argv) < 2 else f'/t/{sys.argv[1]}'
os.system(f'start chrome{page}')
neex profile image
neex • Edited on

Hmmm, I am failing to see how writing a shell script will teach you Python.

jasper_zanjani profile image
Jasper Zanjani

I wonder if you were building a house and trying to use a hammer on a screw, would you be such a smartass if I proffered a screwdriver?

Thread Thread
neex profile image

The whole point is that I am not building a house. I want to build one some day, so I practice my skills by building a table. And than a chair. It will cost me $500 in time and materials. I could of course go and pick one up in Ikea for $25 but that will not make building a house any easier.

jasper_zanjani profile image
Jasper Zanjani

very cool as a demonstration of the Click and Webbrowser libraries, probably the easiest way to demonstrate both at the same time


Thank you.

Thanks for visiting DEV, we’ve worked really hard to cultivate this great community and would love to have you join us. If you’d like to create an account, you can sign up here.