1

Basically the headline.

In Python, I want to take max 280 characters of input from the user, and show a live updating counter on the CLI as the user types the input.(Similar to a Progress bar)

Getting some text to update on the screen is simple, but I don't know how to count the characters as the user is inputting them.

P.S. First-time StackOverflow user, please go easy on me. :)

EDIT: Codebase: https://github.com/Prathamesh-Ghatole/100DaysOfCode-Writer/blob/master/main.py

I don't have a specific code snippet where I want to implement it yet.

But I basically want to take character input from the user in a loop where each iteration does the following:

  1. Take single character input.
  2. update a variable that counts the total number of input characters.
  3. subtract the number of input characters from the character number limit.
  4. Trigger a flag when the character limit is exceeded.

1 Answers1

0

Using pynput package this seems to work.

from pynput.keyboard import Key, Listener
import os

length = 0
char_count = dict()
text = str()


def on_press(key):
    try:
        global text
        global char_count
        global length

        if length >= 280:
            print("[+] Character Limit Excided!")
            return False

        elif key == Key.enter:
            return False

        else:
            os.system("cls")
            if key == Key.space:
                text += ' '
            else:
                text += f"{key.char}"
            char_count[text[-1]] = char_count.get(text[-1], 0) + 1
            length += 1
            print(f"Enter Text: {text}")
            print(f"Characters Left: {280 - length}")
            print(f"Char Count {char_count}")
    except:
        exit()

def main():
    os.system("cls")
    with Listener(on_press=on_press) as listner:
        print("Enter Text: ")
        listner.join()


if __name__ == '__main__':
    main()
Tushar Ghige
  • 121
  • 1
  • 5