有没有办法在 Python 中只接受数字,比如使用 raw_input()
?
我知道我总是可以获得输入并捕获 ValueError
异常,但我很想知道是否可以通过某种方式强制提示只接受数字并卡住任何其他输入。
最佳答案
来自docs :
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:
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 - 在 Python 中只接受数字作为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3144529/