Do you want to add some spice to your command-line interface (CLI) game? Well, bro, have I got news for you! Introducing the curses module Python’s answer to making your CLI experience less boring and more fun.
Now, before we dive into this magical world of curses, let me first explain what it is not. It’s not a fancy new library that will make you rich overnight or solve all your problems. Nope, sorry to disappoint you there. But what it can do for you is add some serious style points to your CLI game and help you create interactive interfaces with ease.
So, let’s get started! To set the stage installing the curses module. If you haven’t already done so, open up your terminal (or command prompt if you’re on Windows) and type:
# This script installs the curses module for Python using the pip package manager.
# First, we need to import the pip module to use its functions.
import pip
# Next, we use the pip module to install the curses module for Python.
pip.main(['install', 'curses'])
# The main function of pip takes in a list of arguments, with the first argument being the command to execute and the following arguments being the options and packages to install.
# The 'install' command tells pip to install the specified packages.
# The 'curses' package is the one we want to install in this case.
# By using the main function of pip, we can easily install packages from within a Python script.
# This is useful for automating the installation process or for creating scripts that require specific packages to be installed.
# Once the script is executed, the curses module will be installed and ready to use in your Python projects.
Once that’s done, let’s create a simple program to test out our new toy. Open up your favorite text editor or IDE and add the following code:
import curses # import curses library for terminal manipulation
from time import sleep # import sleep function from time library for animation effect
def main():
stdscr = curses.initscr() # initialize screen
curses.noecho() # turn off echoing of keys
curses.cbreak() # disable buffered input
stdscr.keypad(True) # enable keyboard arrows
curses.start_color() # enable colors
stdscr.clear() # clear screen
stdscr.addstr("Welcome to the Curses World!") # add string to screen
stdscr.refresh() # refresh screen
while True:
key = stdscr.getkey() # get user input
if key == 'q': # exit program when q is pressed
curses.endwin() # end window and restore terminal settings
break
elif key in ['up', 'down', 'left', 'right']: # handle arrow keys
# use match statement to handle different arrow key inputs
match key:
case 'up': stdscr.move(0, -1) # move cursor up one line
case 'down': stdscr.move(0, 1) # move cursor down one line
case 'left': stdscr.move(-1, 0) # move cursor left one column
case 'right': stdscr.move(1, 0) # move cursor right one column
stdscr.clrtoeol() # clear line to the end of screen
stdscr.refresh() # refresh screen
sleep(0.2) # add delay for animation effect
curses.endwin() # end window and restore terminal settings
if __name__ == '__main__':
main()
This program initializes the curses module, turns off echoing of keys, disables buffered input, enables keyboard arrows, and starts color mode. It then clears the screen and adds a welcome message to it. The while loop listens for user input using the getkey function and handles ‘q’ as an exit key. If any arrow key is pressed, the program moves the cursor accordingly and clears the line to the end of the screen before refreshing it.
Now, let’s run this bad boy! Save your file with a .py extension (e.g., curses_demo.py) and execute it in your terminal:
#!/bin/bash
# This is a bash script that uses the curses library to create a simple interactive program.
# It starts by importing the curses library.
import curses
# Next, it defines a function called main that will be the main body of the program.
def main():
# The curses library is initialized and assigned to the variable stdscr.
stdscr = curses.initscr()
# The curses library is configured to not display user input on the screen.
curses.noecho()
# The curses library is configured to not wait for the user to press enter after each input.
curses.cbreak()
# The curses library is configured to enable special keys like arrow keys to be captured.
stdscr.keypad(True)
# A loop is started to continuously listen for user input.
while True:
# The program waits for the user to press a key and assigns the key to the variable key.
key = stdscr.getch()
# If the user presses the 'q' key, the program exits.
if key == ord('q'):
break
# If the user presses an arrow key, the program moves the cursor accordingly.
elif key == curses.KEY_LEFT:
stdscr.addstr(0, 0, 'Left arrow pressed')
elif key == curses.KEY_RIGHT:
stdscr.addstr(0, 0, 'Right arrow pressed')
elif key == curses.KEY_UP:
stdscr.addstr(0, 0, 'Up arrow pressed')
elif key == curses.KEY_DOWN:
stdscr.addstr(0, 0, 'Down arrow pressed')
# The line is cleared to the end of the screen before refreshing it.
stdscr.clrtoeol()
stdscr.refresh()
# The curses library is reset to its default settings before exiting the program.
curses.nocbreak()
stdscr.keypad(False)
curses.echo()
curses.endwin()
# The main function is called to start the program.
main()
# This script uses the curses library to create a simple interactive program.
# The curses library is initialized and configured to enable special keys to be captured.
# A loop is started to continuously listen for user input.
# If the user presses the 'q' key, the program exits.
# If the user presses an arrow key, the program moves the cursor accordingly and clears the line to the end of the screen before refreshing it.
# The curses library is reset to its default settings before exiting the program.
You should now see the welcome message on your screen, along with some animation effects when you press arrow keys. If you’re feeling adventurous, try adding more features to this program or creating a new one from scratch using the curses module. The possibilities are endless!