Building a CLI Tool on Raspberry Pi: A Complete In-Depth Guide with Practical Code Examples

SBC Programming

CLI tools, which stand for command-line interface tools, are an important part of modern computing. They offer a quick, effective, and scriptable way to connect with systems, automate tasks, and make small tools. CLI tools are especially useful on a Raspberry Pi because they work well with the device’s strengths, which are low resource usage, flexibility, and deep integration with Linux-based environments.

Making a command-line interface (CLI) tool on a Raspberry Pi with Python is a great way to learn how to code, automate systems, and write useful code. You can use command-line interface (CLI) tools for many things, such as keeping an eye on your system, managing files, writing automation scripts, controlling IoT devices, and processing data.

This guide goes into great detail about how to make CLI tools on a Raspberry Pi. It talks about the design principles behind CLI apps, shows how to make them with Python, and gives several real-world code examples that show how to use these tools well.

Understanding CLI Tools and Their Importance

A CLI tool is a program that runs in a terminal and lets users give it commands and arguments. CLI tools are built for speed and efficiency, unlike graphical applications. This lets users do things quickly without having to deal with complicated interfaces.

CLI tools are often the best way to interact with a Raspberry Pi, especially when there is no graphical interface available, like in headless setups. They let users control the system from afar, set up custom workflows, and automate tasks that need to be done over and over.

A simple command-line interface (CLI) tool, for instance, might show system information like how much memory and CPU are being used. A more advanced tool might be able to control hardware parts or work with big datasets.

CLI tools are very useful for anyone who works with Raspberry Pi because they are so flexible.

Setting Up the Development Environment

You need to install the right software on the Raspberry Pi before you can make a CLI tool. Python is usually already installed, which makes it the best language for making CLI apps.

You can check the version of Python directly from the terminal to make sure it was installed correctly. After confirmation, you can install more libraries if you need to.

Argument parsing libraries are an important part of making CLI tools in Python. These libraries let the program take command-line arguments and understand them, which makes the tool flexible and easy to use.

Creating a Basic CLI Tool

The simplest CLI tool is a Python script that prints output based on user input. The following example demonstrates a basic CLI program:

import sys

def main():
    if len(sys.argv) < 2:
        print("Usage: python tool.py <name>")
        return
    
    name = sys.argv[1]
    print(f"Hello, {name}!")

if __name__ == "__main__":
    main()

This script takes a single argument and prints a greeting. It demonstrates how CLI tools receive input through command-line arguments.

While simple, this example forms the foundation for more complex tools.

Improving CLI Tools with argparse

For more advanced functionality, Python’s argparse module provides a structured way to handle arguments.

import argparse

def main():
    parser = argparse.ArgumentParser(description="Simple CLI tool")
    parser.add_argument("name", help="Name to greet")
    args = parser.parse_args()
    
    print(f"Hello, {args.name}!")

if __name__ == "__main__":
    main()

This version improves usability by providing built-in help messages and argument validation. Users can run the tool with a help flag to see usage instructions.

Example: System Monitoring CLI Tool

A practical CLI tool on Raspberry Pi is a system monitor that displays CPU and memory usage.

import argparse
import os

def get_cpu_temp():
    with open("/sys/class/thermal/thermal_zone0/temp") as f:
        return float(f.read()) / 1000

def main():
    parser = argparse.ArgumentParser(description="System Monitor")
    parser.add_argument("--temp", action="store_true", help="Show CPU temperature")
    args = parser.parse_args()
    
    if args.temp:
        temp = get_cpu_temp()
        print(f"CPU Temperature: {temp:.2f}°C")
    else:
        print("Use --temp to display temperature")

if __name__ == "__main__":
    main()

This tool demonstrates how CLI applications can interact with system data and provide useful output.

Example: File Management CLI Tool

CLI tools are often used for file operations. The following example lists files in a directory:

import argparse
import os

def list_files(path):
    files = os.listdir(path)
    for f in files:
        print(f)

def main():
    parser = argparse.ArgumentParser(description="File lister")
    parser.add_argument("path", help="Directory path")
    args = parser.parse_args()
    
    list_files(args.path)

if __name__ == "__main__":
    main()

This tool allows users to quickly inspect directory contents without using a graphical interface.

Example: CLI Tool for GPIO Control

On a Raspberry Pi, CLI tools can interact with hardware. The following example controls an LED:

import argparse
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
LED_PIN = 17
GPIO.setup(LED_PIN, GPIO.OUT)

def main():
    parser = argparse.ArgumentParser(description="LED Control")
    parser.add_argument("state", choices=["on", "off"], help="Turn LED on or off")
    args = parser.parse_args()
    
    if args.state == "on":
        GPIO.output(LED_PIN, GPIO.HIGH)
        print("LED turned ON")
    else:
        GPIO.output(LED_PIN, GPIO.LOW)
        print("LED turned OFF")

if __name__ == "__main__":
    try:
        main()
    finally:
        GPIO.cleanup()

This example shows how CLI tools can directly control physical devices.

Example: Task Automation CLI Tool

CLI tools are ideal for automation. The following script automates a simple backup process:

import argparse
import shutil

def backup(source, destination):
    shutil.copytree(source, destination, dirs_exist_ok=True)
    print("Backup completed")

def main():
    parser = argparse.ArgumentParser(description="Backup tool")
    parser.add_argument("source")
    parser.add_argument("destination")
    args = parser.parse_args()
    
    backup(args.source, args.destination)

if __name__ == "__main__":
    main()

This tool copies files from one directory to another, demonstrating how CLI tools can automate repetitive tasks.

Example: Interactive CLI Tool

Some CLI tools interact with users in real time. The following example creates a simple menu:

def main():
    while True:
        print("1. Say Hello")
        print("2. Exit")
        choice = input("Choose an option: ")
        
        if choice == "1":
            print("Hello from Raspberry Pi CLI tool")
        elif choice == "2":
            break
        else:
            print("Invalid choice")

if __name__ == "__main__":
    main()

This example demonstrates how CLI tools can provide interactive experiences.

Packaging and Running CLI Tools Globally

Once a CLI tool is complete, it can be made executable and accessible from anywhere in the system. This involves adding a shebang line and setting execution permissions.

#!/usr/bin/env python3

After making the script executable, it can be run like a standard command. This enhances usability and allows the tool to be integrated into workflows.

Real-World Applications

You can use CLI tools that run on Raspberry Pi in a lot of real-life situations. They can control devices and keep an eye on conditions in home automation systems. In server environments, they can keep an eye on logs and run processes.

CLI tools help developers speed up their work and do things automatically. In schools, they are a hands-on way to learn how to program and run a computer system.

CLI tools are an important part of the Raspberry Pi ecosystem because they can do so many things.

Best Practices for CLI Tool Development

When making good CLI tools, you should think about how clear and easy they are to use. Users have a better experience when argument names are clear, error messages are helpful, and behaviour is consistent.

Testing is necessary to make sure something works. Scripts should be able to handle unexpected input without crashing and give useful feedback.

Even built-in help messages are a form of documentation that helps users learn how to use the tool correctly.

Conclusion

Making a CLI tool on a Raspberry Pi is a useful and fun project that lets you program, interact with the system, and solve real-world problems. Python lets developers quickly make powerful tools that can do a lot of different things.

CLI tools are a flexible and effective way to work with the Raspberry Pi, from simple scripts to complicated automation systems. Users can make their own tools and improve their skills by learning the ideas and examples in this guide.

This skill is useful not only for Raspberry Pi projects but also for software development and system administration in general.

 

Related posts

Automating Scripts with Bash (Complete Guide with Examples)

Building a Temperature Sensor with Python on a Raspberry Pi: A Complete In-Depth Guide with Practical Code Examples

Node.js Projects on Raspberry Pi with Examples (Complete 2026 Guide)