1

there's my code:

import sys
import keyboard
import rotatescreen
from time import sleep
pd = rotatescreen.get_primary_display()
angel = [90, 180, 270, 0]
for i in range(2):
    for x in angel:
        pd.rotate_to(x)
        sleep(0.5)
if keyboard.is_pressed("p"):
    sys.exit(0)

So the program is working very well, doing his task, but the last 2 lines just don't seem to work. When i press 'p' the program just finishes his work instead of stopping.

CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
FeerQ
  • 11
  • 1
  • 2
    last two lines don't appear to matter since whether or not `keyboard.is_pressed("p")`, the script ends successfully with status `0`. – Kache Jul 06 '22 at 00:25
  • 2
    I believe the `is_pressed()` function checks to see if the key is pressed _at that exact moment_. If you pressed it earlier, the function will not detect that. – John Gordon Jul 06 '22 at 00:30
  • 1
    You need to create a handler for that key combination with an action to execute. For whatever keyboard module you’re using, look up something like “global hook.” – wkl Jul 06 '22 at 01:15
  • Generally speaking, lines of code are executed in order. That part is after the `for` loop, and will only check at the very end, after the loop is done. – CrazyChucky Jul 06 '22 at 01:53

1 Answers1

1

You want to listen for the keyboard event as close to the "execution" of your operation as possible. In your case, that's in the nested loop:

for i in range(2):
    for x in angel:
        if keyboard.is_pressed("p"):
            sys.exit(0)
        pd.rotate_to(x)
        sleep(0.5)

I would also give the documentation a read through, specifically this: Common patterns and mistakes

Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69