Python Forum

Full Version: Type just one character not followed by ENTER
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all! If I remember well,in C++, I could wait an answer to (y/n), the user typing y, not followed by hitting ENTER. Is it possible in python3 ?? Thanks
I just had a post about getting keypress here.
So if i rewrite it a little.
import msvcrt

print('Would you like to go on y/n')
while True:
    ch = msvcrt.getch()
    if ch in b'\x00':
        ch = msvcrt.getch()
    if ch == b'y':
        print('<y> typed going out')
        break
    if ch == b'q':
       break
    else:
       print(f'Key Pressed: {ch}')
Test:
Output:
E:\div_code λ python scan_user.py Would you like to go on y/n Key Pressed: b'n' Key Pressed: b'g' Key Pressed: b't' Key Pressed: b'r' Key Pressed: b'e' <y> typed going out
This is Windows only,as @buran mention Click which is my favorite CLI tool for Python.
Click work cross platform and solve Unicode for all shell(even cmd Windows).
My tutorial about it.
See that i use b'y' to get it to work Python 3.
import click

click.echo('Continue? [yn] ', nl=False)
c = click.getchar()
click.echo()
if c == b'y':
    click.echo('We will go on')
elif c == b'n':
    click.echo('Abort!')
else:
    click.echo('Invalid input :(')
Test:
Output:
E:\div_code λ python yn.py Continue? [yn] # No Enter pressed We will go on