简体   繁体   中英

Exit from loop in python

I want to exit this while loop by pressing Ctrl-C. It doesn't seem to work my way. Any ideas? Thanks n advance

import pyautogui, time

time.sleep(5)
distance = 150
print('Press Ctrl-C to quit.')
try:
    while True:
        pyautogui.dragRel(distance, 0, duration=0.2)
        distance = distance - 5
        pyautogui.dragRel(0, distance, duration=0.2)
        pyautogui.dragRel(-distance, 0, duration=0.2)
        distance = distance - 5
        pyautogui.dragRel(0, -distance, duration=0.2)
except KeyboardInterrupt:
    print('\nDone.')

You should not need the sleep command at all, the following should interrupt on ctrl-C:

n = 0
import time
try:
    while True:
        n += 1
        print n
except KeyboardInterrupt:
    print('\nDone.')

This is assuming that you are running on Linux (where I am testing), on other operating systems that may possibly be different.
If the above does not work, then there must be something about the terminal that you are using to run the code, which is not catching the interrupt.
Try on the python command line:

a = raw_input()

and then press Ctrl-C
you should get something like this:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyboardInterrupt

The raw_input() above assumes python 2.7 for python3 use:

a = input()

expect the same result.

I have tested your code in 3 different terminals (on Ubuntu). When I put coursor to the terminal, left click and the press Ctrl-C, program terminates successfully.

UPD: Strangely enough after this program started to terminate after simply Ctrl-C :-) (no clicking is needed)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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