bignose
bignose

Reputation: 32347

python: Convert input to upper case on screen as it is typed

How can my Python program convert the user's keyboard input to upper case, as though the user has CAPS LOCK enabled?

I want to emulate a program running on a computer which doesn't have any lower-case letters (i.e. a character set more limited than ASCII).

The text input, typed interactively by the user at the keyboard, should be forced to upper case in real time as though that's what the user typed.

The command line interface could use Python's standard cmd library, or something else. The conversion could be done by a custom input stream, or some other way.

I am not interested in completely re-implementing the character-by-character input system; for example, I would like to continue making use of readline if it is available. I only want to translate the resulting stream as it appears visually and as it comes into the program.

There is a Unix terminal attribute, OLCUC, which sounds promising; but it is marked LEGACY in the Single Unix Specification, and its implementation is unreliable (causes garbage for some normal control sequences or Unicode text). So that is not a solution.

Especially important is that the interface should appear visibly indistinguishable from someone actually typing upper case text; the display should only ever show the user's input as the upper case text the program will process.

Upvotes: 0

Views: 1710

Answers (1)

fips
fips

Reputation: 4379

Using getch: http://code.activestate.com/recipes/134892/

Append after stdin.read in __call__ func the following:

try:
    tty.setraw(sys.stdin.fileno())
    ch = sys.stdin.read(1).upper()
    sys.stdout.write(ch)
    ...

You can just do a conditional while (e.g. until user presses enter) to get char by char and echo it as upper case:

getch = _Getch()
text = ''

while True:
    char = getch()
    if ord(char) == 13:  # ascii carriage return
        break
    else:
        text += char

print text

Upvotes: 2

Related Questions