python - 如何在命令行python中接受按键?

标签 python keyboard keypress

Possible Duplicate:
Python read a single character from the user

我希望能够使用 python 用箭头键控制机器人。我的想法是实现看起来像这样的代码......

#!/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"

但问题是我不知道如何获取用户输入。而且我不能使用我发现的基于 GUI 的解决方案,例如 pygame,因为机器人不使用显示器。

非常感谢任何帮助!

最佳答案

一个简单的诅咒示例。查看 curses module 的文档详情。

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 - 如何在命令行python中接受按键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10693256/

相关文章:

python - 给出字典的笛卡尔积

Android:尝试用 View 替换键盘时如何防止 View 跳转/闪烁

c# - 在用户按键上搜索数据 GridView

java - 如何在Java中检测按键

python - Numpy:如何检查 ndarray 中是否存在元组

python - str.format() 引发 KeyError

python - 如何获取图像文件,使用Scrapy

internationalization - 表情符号/国际键盘

ios - 在后台点击时隐藏键盘 - 手势引用问题

javascript - 从javascript触发击键