Pergunta

I was wondering how I might read 140 or less characters from a line in python. Either the user would enter exactly 140 characters, then a newline, or less than 140 and a newline. It appears that raw_input() doesn't have a limit, and that sys.stdin.read(140) will read until it hits 140 characters, regardless of a newline.

EDIT: How would I stop it at 140 characters? Just a hard NO MORE INPUT ALLOWED. Cannot type more.

Ideas?

Max

Foi útil?

Solução

Normally, stdin is line-buffered, which means the program running is not informed about what the user is typing until the user presses Enter (this allows the user to use line-editing commands such as backspace without your program having to do anything extra). However, it is possible to change the terminal to "raw" mode, so that the program will be informed every time the user presses a key. Then, your program can act upon that keypress in whatever way is appropriate. In this case, you'll have to implement line editing such as backspace yourself.

One high-level way to do this is to use the curses library.

Outras dicas

Like

ip = sys.stdin.readline()
if len(ip) > 140:
    print "error: over 140 chars"
    sys.exit()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top