Accepting only numbers as input in Python
有没有办法只接受Python中的数字,比如使用
我知道我总是可以获得输入并捕获
来自文档:
How do I get a single keypress at a time?
For Unix variants: There are several
solutions. It’s straightforward to do
this using curses, but curses is a
fairly large module to learn. Here’s a
solution without curses:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import termios, fcntl, sys, os fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) try: while 1: try: c = sys.stdin.read(1) print"Got character", `c` except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) |
You need the termios and the fcntl
module for any of this to work, and
I’ve only tried it on Linux, though it
should work elsewhere. In this code,
characters are read and printed one at
a time.termios.tcsetattr() turns off stdin’s
echoing and disables canonical mode.
fcntl.fnctl() is used to obtain
stdin’s file descriptor flags and
modify them for non-blocking mode.
Since reading stdin when it is empty
results in an IOError, this error is
caught and ignored.
使用此功能,您可以抓取角色,检查它是否为数字,然后显示它。 不过,我自己没试过。
据我所知,没有。 我从来没有听说过使用Python或任何其他语言的终端可能有这样的事情。
我能想到的最接近假的方法是将终端设置为静默模式(以便输入字符不被回显)和无缓冲模式(这样你就可以输入每个字符的类型,而无需等待结束 ()),然后逐个读取每个输入字符; 如果它是一个数字,打印它并将其附加到字符串,否则丢弃它。 但我甚至不确定终端是否会允许你这样做。