Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accepting only numbers as input in Python

Tags:

python

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

I know I can always get the input and catch a ValueError exception, but I was interested in knowing whether there was someway I could force the prompt to accept only numbers and freeze on any other input.

like image 787
user225312 Avatar asked Apr 29 '26 07:04

user225312


1 Answers

From the 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.

Using this, you could grab the character, check if it's a number, and then display it. I haven't tried it myself, though.

like image 99
Tim Pietzcker Avatar answered May 01 '26 20:05

Tim Pietzcker