Taking only numbers as input in Python

Is there a way to accept only numbers in Python, for example using raw_input()?

I know that I can always get input and catch an exception ValueError, but I was interested to find out if there is something that I can force the invitation to accept only numbers and freeze any other input.

+3
source share
2 answers

From docs :

How to get one keystroke at a time?

For Unix variants: there are several solutions. Its easy to do this using curses, but curses are a fairly large module to learn. Has a curseless solution:

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)

fcntl , , Ive Linux, . , .

termios.tcsetattr() stdins . fcntl.fnctl() stdins . stdin, IOError, .

, , , . .

+2

, . , , Python .

, , ( ) ( , , , ), ; , , . , .

0

Source: https://habr.com/ru/post/1752343/


All Articles