Dear Community,

hopefully someone can explain this to me in simple terms:

I would like to store raw input from a User without waiting for him to press Enter. And would it be possible to still check if the response is one of the predefined options?

My raw input consists of a single character - a number from 1 to 7.
I run the program in a terminal window in Windows.

I looked online and found that to solve this problem, it is necessary to use the msvcrt.getch() function but I don't understand (literally) how to apply this to my code.

I ran the following in the Command line and it worked:
>>> from msvcrt import getch
>>> r = msvcrt.getch()
but I don't know how to apply this to my raw input variable.

This is part of the code I am using now. The good thing is that it checks if the input is one of the predefined options. But the problem is that, the input is stored only after a user presses Enter.

userResponse = ''
while userResponse not in ['1','2','3','4','5','6','7']:
    userResponse = raw_input("Choose a number from 1 to 7")
    if userResponse == '1':
        output = "1\n"
        results.write(output)
    if userResponse == '2':
        output = "2\n"
        results.write(output)
    ......

I will appreciate any help!

Woh, I just fixed this myself :D

This is what does the trick:

import msvcrt
from msvcrt import getch

print "Choose a number from 1 to 7: "
userResponse = ''
while userResponse not in ['1','2','3','4','5','6','7']:
    userResponse = msvcrt.getch()
    if userResponse == '1':
        output = "1\n"
        results.write(output)
    ....

But this works only in Windows. What would be a solution in Linux??

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.