magmax / python-readchar

Python library to read characters and key strokes
MIT License
153 stars 46 forks source link

Limiting the number of characters of a user input #12

Closed ghost closed 2 years ago

ghost commented 8 years ago

Hello there,

I was looking for a easy way to limit the number of characters that can be input into a raw_input and someone suggested readchar would do the trick and sent me the following piece of code:

import readchar
import sys

string = ""

while len(string) < 20:
    c = readchar.readchar()
    sys.stdout.write(c)
    string += c

print '\n' + string

Which worked fine by itself but when I try to implement it to this code: https://gist.github.com/lovemac15/c5e71e0b8aa428693e5b I get all sorts of errors, from encoding to skipping the input altogether.

So my question here is basically: is it possible to use readchar in a raw_input/input? How?

Thanks for your time! :D

magmax commented 8 years ago

Well.. it is not possible to use readchar in a raw_input/input, but it is possible to use it instead.

You can see an example in Inquirer, the project that required me to write readchar: https://github.com/magmax/python-inquirer ... hmmm after having a look on it, it seems to be quite complex to be used as example :)

Just use readchar in a loop:

import readchar

def read_line():
    line = ''
    while True:
        c = readchar.readchar()
        if c == readchar.key.CR:
            return line
        line += c
magmax commented 8 years ago

Another point: After having a look to your piece of code, I suggest you to see python-inquirer(https://github.com/magmax/python-inquirer) or even the standard library "cmd" (https://docs.python.org/3.5/library/cmd.html). Maybe any of them can help you.