用按键中断Python无限循环

时间:2014-08-15 15:18:32

标签: python infinite-loop

我正在编写一个简单的脚本来防止我的计算机入睡(没有管理员权限),并且它以一个无限循环为中心,而#34;而真正的"行:

import time, win32api
cursorX = 0
cursorY = 0
while True:
    cursorX, cursorY = win32api.GetCursorPos()
    time.sleep(600)
    cursorX = cursorX + 10
    win32api.SetCursorPos((cursorX,cursorY))
    cursorX, cursorY = win32api.GetCursorPos()
    time.sleep(600)
    cursorX = cursorX - 10
    win32api.SetCursorPos((cursorX,cursorY))

现在,我可以通过一个简单的Ctrl + C来中断这个,但是我想要比这更干净地杀掉它。是否有一种简单的方法来编写条件以等待按键按下以消除循环?我猜它可能涉及一个我不太了解的事件。

2 个答案:

答案 0 :(得分:3)

我添加的最后三行将允许您在按下任何键的情况下突破循环。别忘了导入msvcrt

import time, win32api
import msvcrt
cursorX = 0
cursorY = 0
while True:
    cursorX, cursorY = win32api.GetCursorPos()
    time.sleep(600)
    cursorX = cursorX + 10
    win32api.SetCursorPos((cursorX,cursorY))
    cursorX, cursorY = win32api.GetCursorPos()
    time.sleep(600)
    cursorX = cursorX - 10
    win32api.SetCursorPos((cursorX,cursorY))
    if msvcrt.kbhit():
        if ord(msvcrt.getch()) != None:
            break

答案 1 :(得分:3)

清除CTRL-C的使用方法是使用try-except来捕获KeyboardInterrupt:

try:
    while True:
        ...
        ...
except KeyboardInterrupt:
    exit