Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 键盘中断赢得';即使条件明显满足,也不能工作_Python_Error Handling_Pynput - Fatal编程技术网

Python 键盘中断赢得';即使条件明显满足,也不能工作

Python 键盘中断赢得';即使条件明显满足,也不能工作,python,error-handling,pynput,Python,Error Handling,Pynput,当用户按下键盘箭头时,我正在打印以下内容: You picked left! You picked left! You picked right! 当用户按下escape键时,您按下escape键后,键盘中断应立即启动,但它没有你按下了escape已打印,但仅此而已。同样的行为也发生在JupyterLab和PyCharm中 为什么不引发键盘中断? from pynput.keyboard import Key, Listener class CoolTrick: @static

当用户按下键盘箭头时,我正在打印以下内容:

You picked left! 
You picked left! 
You picked right!
当用户按下escape键时,您按下escape键后,
键盘中断
应立即启动,但它没有<代码>你按下了escape已打印,但仅此而已。同样的行为也发生在JupyterLab和PyCharm中

为什么不引发键盘中断?

from pynput.keyboard import Key, Listener

class CoolTrick:

    @staticmethod
    def _on_press(key):

        if key == Key.left:
            print('\rYou picked left!',             end='       ')

        if key == Key.right:
            print('\rYou picked right!',            end='       ')

        if key == Key.esc:
            print('\rYou pressed escape!',          end='       ')

            raise KeyboardInterrupt('You interrupted the process by'
                                    'pressing escape.')

    def run(self):
        while True:
            while True:

                with Listener(
                        on_press=self._on_press) as listener:
                    listener.join()

ct = CoolTrick()

ct.run()

如果在IDE之外运行它,它能工作吗?如果改用
raisesystemexit
如何?(
SystemExit
最终可能更正确,但找出
键盘中断
不起作用的原因是值得的。)您还可以检查以确保在
join
处重新出现异常:
尝试:
侦听器.join()
除了e:
打印(“获得某种异常”)
升起
You pressed escape! 
You picked right!