-1

I'm making a Python script and wanted to let the user use the Arrow Keys to navigate through the screens.

I found this answer from @yatsa, that really worked for the Arrows: https://stackoverflow.com/a/46449300/11903801

#!/usr/bin/python

import click

printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

while True:
    click.echo('Continue? [yn] ', nl=False)
    c = click.getchar()
    click.echo()
    if c == 'y':
        click.echo('We will go on')
    elif c == 'n':
        click.echo('Abort!')
        break
    elif c == '\x1b[D':
        click.echo('Left arrow <-')
    elif c == '\x1b[C':
        click.echo('Right arrow ->')
    else:
        click.echo('Invalid input :(')
        click.echo('You pressed: "' + ''.join([ '\\'+hex(ord(i))[1:] if i not in printable else i for i in c ]) +'"' )

This example is supposed to identify if it was pressed left-key or right-keys and it also prints the "py-string representation" of any other keyboard key pressed.

Said that, I had to change the code to make it work for me...
When I ran the code above it didn't identify the Left and Right arrows.
Instead it printed to me:

You pressed "\xe0K" (for left arrow)

and

You pressed "\xe0M" (for right arrow)

What did I do?
Replace that values in elifs with this the console printed to me, and IT WORKED!

Ok, GOOD, so next I wanted to identify the "Enter Key", so I ran the script, press Enter, and it printed to me: You pressed "\xd"

So, what did I do?
Created a new conditional using this string the console printed to me.

BUT...

    elif c == '\xd':
             ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-2: truncated \xXX escape

Process finished with exit code 1

So, I don't know what's the problem, I tried to search the web but didn't found anything that explains it to me.

I'm using Windows 7.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Renato
  • 3
  • 5
  • 1
    STRONG SUGGESTION: If you really want a text-mode UI, do *NOT* rely on ASCII cursor control characters. Use a [curses](https://docs.python.org/3/library/curses.html#module-curses) library: https://docs.python.org/3/howto/curses.html – paulsm4 Aug 08 '19 at 19:03
  • @paulsm4 Thanks, now I'm using tkinter. :) – Renato Mar 17 '22 at 10:10

1 Answers1

0

I would suggest using (or referring to) the keyboard library. The benefit here is that you'll be able to comply with Windows and Linux (OSX seems to be experimental in this library)

To answer your question specifically, it seems like you should be using 0x0d for Enter

Edit: Add link to Enter key

Zoidberg
  • 425
  • 3
  • 10