如何在命令行python中接受按键? [英] How to accept keypress in command line python?
本文介绍了如何在命令行python中接受按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
Python从用户读取单个字符
Possible Duplicate:
Python read a single character from the user
我希望能够使用python使用箭头键控制机器人.我的想法是实现看起来像这样的代码...
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"
但是问题是我不知道如何获得用户输入.而且,由于机器人不使用显示器,因此我无法使用基于pygame的基于GUI的解决方案.
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.
非常感谢您的帮助!
推荐答案
一个简单的诅咒示例.有关详细信息,请参见 curses模块的文档.
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()
这篇关于如何在命令行python中接受按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文