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/