python - 在 Python 中只接受数字作为输入

标签 python

有没有办法在 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/

相关文章:

python - 使用 Python 和 datetime 模块根据 TimeUUIDType 从 Cassandra 获取列范围

c++ - C++ 应用程序 (Sci)Python 之间的数据交换

python - Tensorflow实现crf损失

python - 可用 **kwargs 列表

docker 镜像上的 Python ScriptEngine null

python - elasticsearch python pycharm

Python 字典到字符串

python - 将参数传递给python中的装饰器

python - 如何告诉 Python 在 pylab.show() 之后结束?

javascript - 从 Python BeautifulSoup 中的 javascript 源中提取值