[英]Python - react to custom keyboard interrupt
I am writing python chatbot that displays output through console. 我正在编写通过控制台显示输出的python chatbot。 Every half second it asks server for updates, and responds to message.
每隔半秒,它会请求服务器进行更新,并响应消息。 In the console I can see chat log.
在控制台中,我可以看到聊天记录。
This is sufficient in most cases, however, sometimes I want to interrupt normal workflow and write custom chat answer myself. 在大多数情况下,这已经足够了,但是,有时我想打断正常的工作流程并自己编写自定义聊天回答。 I would love to be able to press a button (or combination) that would switch to "custom reply mode".
我希望能够按下将切换到“自定义回复模式”的按钮(或组合键)。 What is the best way to do that, or achieve similar result?
做到这一点或取得相似结果的最佳方法是什么?
Thanks a lot! 非常感谢!
在sys.stdin
上使用select.select()
将允许您检查是否在终端上按下了键。
Given the comments in the previous answer, you need a non-blocking function to tell whether any keys were pressed rather than something that triggers as soon as the key was pressed. 给定上一个答案中的注释,您需要一个非阻塞函数来告诉您是否按下了任何按键,而不是在按下按键后立即触发的功能。
I would therefore recommend using some of the terminal APIs available on your OS. 因此,我建议您使用操作系统上可用的某些终端API。 Typically this would be curses or the win32 console API.
通常这是curses或win32控制台API。 However, I have written a common wrapper to both in asciimatics .
不过,我已经写在一个共同的包装既asciimatics 。 The
get_event()
method on the Screen
should provide a simple cross-platform way of getting mouse and keyboard events. Screen
上的get_event()
方法应提供一种获取鼠标和键盘事件的简单跨平台方法。 To see if it was a keyboard event, check the type of returned event. 要查看是否是键盘事件,请检查返回事件的类型。 If there was no event, you'll get a return code of
None
, but if it was a key pressed, you'll get KeyboardEvent
. 如果没有事件,您将获得
None
的返回码,但是如果按下了键,则将得到KeyboardEvent
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.