Handling keyboard events in python

点点圈 提交于 2019-12-02 16:40:18

问题


How can I handle keyboard events in python? More exactly I need to manage keyboard arrows and some other keys for my command-line application. Is there a module for this or I need to handle key by key using for example "if get(key)==(mykey): do something" (it's pseudo-code)? I'm on Gnu/Linux OS.


回答1:


You're probably looking for a python (n)curses library. This will allow to "get around" your terminal buffering and work with key-presses directly.




回答2:


Would the cmd module suit your needs? It handles command-line history through the arrow keys, for instance, as well as completion.

If you need to catch a single key, there is a cross-platform recipe for this (see also Python read a single character from the user on StackOverflow).




回答3:


jkerian's curses suggestion is a good one, and is the one to use if you're working with Unix/Linux/etc. (which you are), but if you ever end up working in a Windows environment, then you'll definitely want to check out pywin32 and its win32con module, which wraps the Windows API's Console functions and structs.




回答4:


I found another interesting module that's straightforward to use and I'll use it! The module is readline and you just need to import it to have a bash shell (handle keyboard, history-list, etc) "simulation". It's for *nix systems. I'm at beginning with python language and I don't know all modules yet. readline



来源:https://stackoverflow.com/questions/6348952/handling-keyboard-events-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!