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.