0

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). The output I expect is:

   1
   2
   3
  "Enter" key pressed!
   5

Is it possible to do using python?

EDIT: I need to be able to get the keystroke in the background, so that it works while another application is open

  • use `continue`. – Vinay Hegde Jul 21 '19 at 09:38
  • 1
    consider using the [`keyboard`](https://pypi.org/project/keyboard/) packege – Tomerikoo Jul 21 '19 at 09:39
  • 1
    Do you want to know how to read the keyboard while the for is running? Or are you just asking how to go about skipping the iteration? – Mike Jul 21 '19 at 09:40
  • @Mike, I wanna know how to read the keyboard while the for is running – Trafalgar Law Jul 21 '19 at 09:55
  • You need to simultaneously sleep and check for keypresses. That requires threading. You may be able to do that by modifying the solution [here](https://stackoverflow.com/a/19655992/3830997). If you don't want to wait till the end of the 2s sleep to check for pending keys, you could break the sleep into smaller parts, e.g., 20 0.1s sleeps. Check for pending keypresses after each one, and then break to the next iteration if a keypress occurred. – Matthias Fripp Jul 21 '19 at 10:00
  • You may also find some of the solutions [here](https://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python) useful. They focus on checking for a keypress, but giving up after a certain length of time (2s in your case). You could modify them to do the next iteration if the timeout is reached, otherwise skip it. – Matthias Fripp Jul 21 '19 at 10:07

2 Answers2

1

You can catch KeyboardInterrupt to detect using pressing "Ctrl+c"

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
Sunitha
  • 11,777
  • 2
  • 20
  • 23
0

Using the keyboard module, this can be achieved easily, just note you have to be pressing the key when the if is evaluated...

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
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124