Creating CLI Utilities with Python

If you do any sort of automation, you have probably done a fair amount of work using the CLI on your computer.   This is applicable regardless of platform. If you use Python you might have asked yourself how you could start making your own command line utilities to help you in your daily tasks.  That very question is the topic of todays article.

We will start by discussing how to get your python applications without having to type python at the beginning.  Then we will discuss how to properly parse the command line arguments so you can pass in the parameters you need.  Finally we will create a python utility you can use for running ping tests against other devices on your network.

Running scripts without typing python

This part is pretty easy as are about to see. But it does vary depending on the platform you are using.  Unix variants like Linux, Macos, etc… have one way of doing things. Windows has a different way of doing things.

Beyond what is described here, you could also compile your python scripts to native binaries for the platform you are using.  But that is the topic of a future article.

Linux and Macos

If you have ever inspected the shell scripts on your unix/linux system, you have probably noticed on the first line a comment similar to:

#!/bin/bash

This line is called the shebang. This line is optional in all of your scripts.  However, if it is there, it tells your terminal which command interpreter to use.  This is what allows you to run a command without specifying which interpreter to use.  In the example above, it is telling the terminal to run the script with the bash command interpreter.  If you are writing a python application, you need to specify a python command interpreter.

If you happen to be writing scripts that work in both python and python 3, you can specify the following shebang at the top of your script:

#!/usr/bin/env python

However, if you have switched to python 3 development, which you should have by now, you should specify that your script will use the python 3 interpreter.  That would look like this:

#!/usr/bin/env python3

Now that you have added the shebang argument at the top of your script, you can now run your scripts without having to first type python.  You might need to add execute permissions to your script by running chmod +x myscriptname.py

Another fun fact, you don’t actually need to have a .py file extension to work.  Now that you have the shebang directive at the top, the system will already know it is a python script and execute it accordingly.

Windows

It is too bad windows does not listen to the shebang directive at the top of the script. It would make this process a bit easier.  That said, it is still not that hard.  What you need to do is associate .py files with the python.exe application on your computer.  This can be done via the GUI, or via the cli.

Associate via the GUI

  1. find any .py file on your computer, right click on it, select properties
  2. On the general tab, Click Change
  3. Browse to where python.exe is located your computer (Usually C:\python3\python.exe or similar )
  4. Select python.exe
  5. Click Ok

Microsoft also alternative instructions here.

Associate via CLI

Before you begin, you need to know the path to python.exe

  1. Open an elevated powershell or command prompt window
  2. Run the following to create the file association: assoc .py=Python.File
  3. Next, run the following to tell windows to use python.exe to open .py files: ftype Python.File=C:\Path\to\pythonw.exe “%1” %*

**Note, remember to replace C:\Path\to\pythonw.exe with the actual path to pythonw.exe

Command line arguments

Command line arguments are the options you specify when you run your script.  For example, we will be creating a ping utility.  You might want to run the following command:

pyping 8.8.8.8

In this case our script is called pyping, and the argument is 8.8.8.8.  In this section, we will discuss how to handle those arguments.

First thing we need to do is install the argparse utility.  This is not the only way to parse command line arguments.  But it is the best way to do it in Python (in my opinion).  To install argparse, run:

pip install argparse

Now that we have our prerequisites installed, let’s create the skeleton of our program:

#!/usr/bin/env python3

#import argparse library
import argparse

#Set description to be printed when using help command
parser = argparse.ArgumentParser(description=’A utility for pinging servers’)

#Add cli arguments and help text
parser.add_argument(‘–host’, help=”What hostname or IP to ping”)
parser.add_argument(‘–count’, help=”How many times to ping host. Default: 4″, default=4)

args = parser.parse_args()
#Print out arguments
print(args)

If you save the above and run pyping.py it will print out what the values are for each of the arguments we specified.  In the code above we set a default value for count to 4. But we did not set a default value for host.  You can see that reflected in the output:

seans-macbook:cli-utility sean$ python pyping.py
Namespace(count=4, host=None)

If you run pyping.py –help you will see even more help text:

seans-macbook:cli-utility sean$ python pyping.py –help
usage: pyping.py [-h] [–host HOST] [–count COUNT]

A utility for pinging servers

optional arguments:
-h, –help show this help message and exit
–host HOST What hostname or IP to ping
–count COUNT How many times to ping host. Default: 4

Finally, you run run pyping –host google.com you should see that the host value is properly set:

seans-macbook:cli-utility sean$ python pyping.py –host google.com
Namespace(count=4, host=’google.com’)

Creating a usable tool

Now that we know how to properly parse arguments, let’s create a working ping utility.  We will start by installing pythonping :

pip install pythonping

Next we will import it into our program:

from pythonping import ping

Next, we can add a line to actually run the ping command and print the output to the screen:

print(ping(args.host, count=args.count))

Your complete program should now look like this:

#!/usr/bin/env python3

#import argparse library
import argparse
from pythonping import ping

#Set description to be printed when using help command
parser = argparse.ArgumentParser(description=’A utility for pinging servers’)

#Add cli arguments and help text
parser.add_argument(‘–host’, help=”What hostname or IP to ping”)
parser.add_argument(‘–count’, help=”How many times to ping host. Default: 4″, default=4, type=int)

#Parse Arguments
args = parser.parse_args()

#Ping host X Times
print(ping(args.host, count=args.count))

Summary

As you  have seen it is easy to create command line utilities that are cross-platform and easy to use in Python. Be sure to always include useful help text in your utility and comments throughout your script to ensure it is easy to use and easy to debug.

Be the first to comment on "Creating CLI Utilities with Python"

Leave a comment

%d bloggers like this: