简体   繁体   English

当按下某个键时,如何跳过for循环中的迭代?

[英]How to skip an iteration in a for loop when a certain key is pressed?

So I have a loop like this: 所以我有这样一个循环:

import time

for i in range(100):
    print(i)
    time.sleep(2)

I want to to be able skip an iteration of that loop by pressing a key on the keyboard (for example Enter). 我希望能够通过按键盘上的某个键(例如Enter)来跳过该循环的迭代。 The output I expect is: 我期望的输出是:

   1
   2
   3
  "Enter" key pressed!
   5

Is it possible to do using python? 可以使用python吗?

EDIT : I need to be able to get the keystroke in the background, so that it works while another application is open 编辑 :我需要能够在后台获得击键,以便在另一个应用程序打开时可以工作

You can catch KeyboardInterrupt to detect using pressing "Ctrl+c" 您可以通过按“ Ctrl + c”来捕获KeyboardInterrupt进行检测

for i in range(100):    
    try:
        time.sleep(2)
    except KeyboardInterrupt:     
        print ('Ctrl+c key pressed!')
        continue

    print(i)

Sample Output 样本输出

0
^CCtrl+c key pressed!
2
3
^CCtrl+c key pressed!
5
6
7

Using the keyboard module, this can be achieved easily, just note you have to be pressing the key when the if is evaluated... 使用keyboard模块,可以轻松实现这一点,只需注意在评估if时必须按下键。

In [1]: import time, keyboard as kb

In [2]: for i in range(10):
   ...:     if kb.is_pressed('enter'):
   ...:         print('enter is pressed, skipping {}'.format(i))
   ...:     else:
   ...:         print(i)
   ...:     time.sleep(1)
   ...:     
0

1



enter is pressed, skipping 2



enter is pressed, skipping 3





enter is pressed, skipping 4




enter is pressed, skipping 5


6
7
8


enter is pressed, skipping 9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM