Python Forum
Type just one character not followed by ENTER
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Type just one character not followed by ENTER
#1
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
Reply
#2
https://pypi.org/project/readchar/
https://pypi.org/project/getkey/
https://pypi.org/project/getch/

Click also provides this as functionality http://click.pocoo.org/5/utils/#getting-...m-terminal

I think recently a noticed yet another one
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [solved] unexpected character after line continuation character paul18fr 4 3,461 Jun-22-2021, 03:22 PM
Last Post: deanhystad
  SyntaxError: unexpected character after line continuation character siteshkumar 2 3,216 Jul-13-2020, 07:05 PM
Last Post: snippsat
  Type hinting - return type based on parameter micseydel 2 2,520 Jan-14-2020, 01:20 AM
Last Post: micseydel
  how can i handle "expected a character " type error , when I input no character vivekagrey 2 2,783 Jan-05-2020, 11:50 AM
Last Post: vivekagrey
  How to recognize space or enter as one-character input? Mark17 5 5,684 Oct-17-2019, 08:19 PM
Last Post: jefsummers
  Replace changing string including uppercase character with lowercase character silfer 11 6,258 Mar-25-2019, 12:54 PM
Last Post: silfer
  SyntaxError: unexpected character after line continuation character Saka 2 18,609 Sep-26-2017, 09:34 AM
Last Post: Saka

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020