k = stdscr.getch()
if k == curses.KEY_UP:
sys.stdout.write('KEY_UP')
elif k == curses.KEY_F1:
sys.stdout.write('KEY_F1')
elif k == 113:
break
else:
pass
https://docs.python.org/2/library/curses.html
The above code can be used to detect 'q' and arrow_up. However, it cannot be used to detect F1.
Question> Is there a way in python curses that I can use to detect the special function keys?
[Update]
My terminal type is xterm.
elif k == 269: # 'F5'
elif k == 270: # 'F6'
elif k == 271: # 'F7'
elif k == 272: # 'F8'
elif k == 273: # 'F9'
elif k == 27: # 'ESC'
special_keys = [stdscr.getch(), stdscr.getch(), stdscr.getch(), stdscr.getch()]
if special_keys == [91, 49, 49, 126]:
sys.stdout.write('F1\n')
if special_keys == [91, 49, 50, 126]:
sys.stdout.write('F2\n')
if special_keys == [91, 49, 51, 126]:
sys.stdout.write('F3\n')
if special_keys == [91, 49, 52, 126]:
sys.stdout.write('F4\n')
Based on the suggestions from @pbuck, I tested my terminal and listed the results above. I am not sure whether this solution is portable or not. Since @pbuck only suggested that I should use the next two keys after ESC. For my case, I have to extract the next four keys.