Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neutralvibes/43b6b6c912c548dd36361ec407d0eaff to your computer and use it in GitHub Desktop.
Save neutralvibes/43b6b6c912c548dd36361ec407d0eaff to your computer and use it in GitHub Desktop.
Python terminal cursor

Controlling cursor colors and movement in python

I recently wanted to color output in a minimal way for a commandline utility I was writing so came up with this little class.

import sys

class Cursor:
    class Color:
        BLACK="\u001b[30m"
        RED="\u001b[31m"
        GREEN="\u001b[32m"
        YELLOW="\u001b[33m"
        BLUE="\u001b[34m"
        MAGENTA="\u001b[35m"
        CYAN="\u001b[36m"
        CYAN="\u001b[37m"
        RESET="\u001b[0m"
        NONE="\u001b[0m"

        def wrap(text, color):
            return "%s%s%s" %(color, text, Cursor.Color.RESET)

    def setColor(color):
        sys.stdout.write(color)
    
    def print(text, color):
        print(Cursor.Color.wrap(text, color))

    def reset():
        Cursor.setColor(Cursor.Color.RESET)

    class Move:
        def up(by):
            return "\u001b[%dA" % by

        def down(by):
            return "\u001b[%dB" % by

        def forward(by):
            return "\u001b[%dC" % by
            
        def back(by):
            return "\u001b[%dD" % by

        def to(x, y):
            return "\u001b[%d;%dH" %(x, y)

Instance not required

No need for cursor = Cursor(). Just use it directly.

Cursor.print("Test line in green", Cursor.Color.GREEN)

Maybe shorten access

If using it more than a couple of times I tend to use variables as shortcuts.

C = Cursor
CC = Cursor.Color
CM = Cursor.Move
CP = Cursor.print

CP("Test line in red", CC.RED)

You coud rename the Cursor class to shorten forever.

Examples

Set cursor color

C = Cursor # Shorten access

C.setColor(C.Color.MAGENTA)
print('This should be magenta')
print('The color is not reset for additional output!')
C.reset() # Set cursor back to normal

print('Back to normal\n')

Get a string to be eventually printed wrapped in a color.

CC = Cursor.Color # shortened access

redTxt = CC.wrap('red', CC.RED)
blueTxt = CC.wrap('blue', CC.BLUE)
greenTxt = CC.wrap('green', CC.GREEN)

print("Red: %s, Blue: %s, Green: %s " % (redTxt, blueTxt, greenTxt))
print('Back to normal\n')

Print a whole line in a color

C = Cursor # shortened access. Coud use `Cursor`
CC = Cursor.Color # shortened access

C.print("Shortcut calls wrap for you with the auto reset and prints the line", CC.GREEN)
print('Back to normal')

Move cursor position

Move cursor back/forward/up/down

CM = Cursor.Move

# Return string codes
up = CM.up(2)  # Value is number of positions
back = CM.back(2)

Prompts: Example

Confirmation input with default value.

  • Colored question
  • Colored responses
import sys

# Insert the Cursor class either via import or copy & paste here

C = Cursor # Shorten access - use whatever you want
CC = Cursor.Color # as above

def promptBool(*,prompt='Confirm', default=False):
    sys.stdout.write('{} [Y/n]: {}{}'.format(prompt, 'Y' if default else 'N', Cursor.Move.back(1)))
    ans = input().lower()
    return True if ans == 'y' else False

if promptBool(prompt= CC.wrap('Do I look fat in this?', CC.BLUE)):
    C.print('I hate you!', CC.RED)
else:
    C.print('Marry me!', CC.MAGENTA)
    

There is far more that can be done, but it might be a starting or end point for others...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment