简体   繁体   中英

read 140 or less characters from python stdin

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

Like

ip = sys.stdin.readline()
if len(ip) > 140:
    print "error: over 140 chars"
    sys.exit()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM