簡體   English   中英

在python中退出循環

[英]Exit from loop in python

我想通過按Ctrl-C退出while循環。 看來這行不通。 有任何想法嗎? 謝謝你提前

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.')

您根本不需要睡眠命令,以下命令應在ctrl-C上中斷:

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

假設您正在Linux(我正在測試的地方)和可能不同的其他操作系統上運行。
如果上述方法不起作用,則您的終端上一定有一些您正在用來運行代碼的東西,它沒有捕獲中斷。
嘗試在python命令行上:

a = raw_input()

然后按Ctrl-C
你應該得到這樣的東西:

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

上面的raw_input()假設python 2.7適用於python3:

a = input()

期望得到相同的結果。

我已經在3個不同的終端(在Ubuntu上)測試了您的代碼。 當我將光標移至終端時,單擊鼠標左鍵並按Ctrl-C,程序將成功終止。

UPD:只需按Ctrl-C :-),該程序就開始終止后就足夠奇怪了(不需要單擊)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM