Skip to content

Instantly share code, notes, and snippets.

@JuniorPolegato
Created June 13, 2013 21:05
Show Gist options
  • Save JuniorPolegato/5777348 to your computer and use it in GitHub Desktop.
Save JuniorPolegato/5777348 to your computer and use it in GitHub Desktop.
Input with filter by type and characters with Python in a Linux terminal
#!/bin/env python
# -*- coding: utf-8 -*-
# Author.....: Junior Polegato
# Date.......: 13 Jun 2013
# Description: Input with filter by type and characters with
# Python in a Linux terminal
import sys, tty, termios
import locale
CODING = locale.setlocale(locale.LC_ALL, '').split('.')[-1]
def select_input(prompt, valids, return_type, maximum, auto_exit=True,
is_invisible=False, invisible_char='*'):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setraw(fd)
sys.stdout.write(prompt)
if return_type == bool:
maximum = 1
if not valids:
valids = '01NY'
else:
valids = valids.upper()
if type(valids) == str:
valids = valids.decode(CODING)
ret = ''
while True:
c = ''
while True:
t = sys.stdin.read(1)
try: # coding test
c = (c + t).decode(CODING)
except:
c += t
continue
try: # return type test
if c == '\r':
break
if return_type == str:
c.encode(CODING)
elif return_type != bool:
return_type(c)
break
except:
sys.stdout.write('\x07') # Beep
c = ''
continue
if c == '\r': # Enter
if ret: break
elif c == '\x7F' and ret: # Backspace
sys.stdout.write('\b \b')
ret = ret[:-1]
elif len(ret) < maximum and (not valids or
return_type == bool and c.upper() in valids or
c in valids): # Valid
if is_invisible:
sys.stdout.write(invisible_char)
else:
sys.stdout.write(c)
ret += c
if len(ret) == maximum and auto_exit:
break
else: # Invalid
sys.stdout.write('\x07') # Beep
sys.stdout.write('\r\n')
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
if return_type == str:
return ret.encode(CODING)
elif return_type == bool:
return bool(valids.index(c.upper()) % 2)
return return_type(ret)
if __name__ == "__main__":
idade = select_input('Idade: ', None, int, 2)
print type(idade), idade
characters = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"ÃÀÁÂÉÊÍÕÓÔÚÜÇÄËÏÖÑÈÌÒÙÎÛÝŸÅÆ"
"ãàáâéêíõóôúüçäëïöñèìòùîûýÿåæ ")
nome = select_input('Nome: ', characters, unicode, 30, False)
print type(nome), nome
characters = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"ÃÀÁÂÉÊÍÕÓÔÚÜÇÄËÏÖÑÈÌÒÙÎÛÝŸÅÆ"
"ãàáâéêíõóôúüçäëïöñèìòùîûýÿåæ ")
amigo = select_input('Amigo: ', characters, str, 30, False)
print type(amigo), amigo
tem_carro = select_input('Tem carro? ', '01NSNY', bool, 1)
print type(tem_carro), tem_carro
senha_numerica = select_input('Senha: ', None, int, 6, True, True)
print type(senha_numerica), "%06i" % senha_numerica
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment