Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accept keypress in command line python? [duplicate]

Tags:

Possible Duplicate:
Python read a single character from the user

I am looking to be able to control a robot with the arrow keys using python. And my idea was to implement code that looked something like this...

#!/usr/bin/env python # control a robot using python exit = 0 while exit == 0:   keypress = ##get keypress, if no key is pressed, continue##   if keypress == 'q':     exit = 1     break   elif keypress == KEY_UP:     ##robot move forward##   elif keypress == KEY_DOWN:     ##robot move backward## print "DONE" 

However the problem is that I do not know how to get the users input. And I cannot use a GUI based solution like pygame from what I have found because the robot does not use a display.

Any help is very much appreciated!!

like image 926
Elmer Avatar asked May 21 '12 22:05

Elmer


People also ask

How do I listen for keypress in Python?

To detect keypress, we will use the is_pressed() function defined in the keyboard module. The is_pressed() takes a character as input and returns True if the key with the same character is pressed on the keyboard.

How do I make python wait for a pressed key?

In Python 2 use raw_input(): raw_input("Press Enter to continue...") This only waits for the user to press enter though. This should wait for a keypress.


1 Answers

A simple curses example. See the docs for the curses module for details.

import curses stdscr = curses.initscr() curses.cbreak() stdscr.keypad(1)  stdscr.addstr(0,10,"Hit 'q' to quit") stdscr.refresh()  key = '' while key != ord('q'):     key = stdscr.getch()     stdscr.addch(20,25,key)     stdscr.refresh()     if key == curses.KEY_UP:          stdscr.addstr(2, 20, "Up")     elif key == curses.KEY_DOWN:          stdscr.addstr(3, 20, "Down")  curses.endwin() 
like image 108
dwblas Avatar answered Oct 31 '22 09:10

dwblas