【问题标题】:how to stop python program when time.sleep() is in progressing当 time.sleep() 正在进行时如何停止 python 程序
【发布时间】:2021-08-04 09:36:45
【问题描述】:

我制作了一个机器人来控制我的鼠标和键盘,以使我玩游戏更容易,但不知何故我无法轻易停止该程序... 我在按下进入程序时创建了一个带有条件的循环被停止,但 time.sleep() 正在进行的 dnt 允许这种情况发生,但是我不能制作整数条件,因为 我希望我的程序不可停止我的意思是当我按下键盘上的一个键时它必须停止 例如

import keyboard
import time

while True:
    print('hello world')
    time.sleep(3)
    if keyboard.is_pressed('enter'):
        break

我知道我可以按住“进入”按钮 3 秒,但我的真实程序的 time.sleep() 持续时间大于 1 分钟,我无法一直按住进入是否有任何其他代码,例如 time.sleep() 可以用来解决我的问题?

【问题讨论】:

    标签: python time bots sleep


    【解决方案1】:

    与其睡 3 秒,不如睡 30 次 0.1 秒的小睡?值得深思。

    import keyboard
    import time
    
    enter_pressed = 0
    while True:
        print('hello world')
        time.sleep(0.1)
        if keyboard.is_pressed('enter'):
            enter_pressed += 1
        else:
            enter_pressed = 0
    
        if enter_pressed >= 10:
            break # enter pressed for 1 sec
    

    【讨论】:

    • 他们为什么要在那个时候睡觉
    • 用于粒度精细控制
    • 我的真实程序持续时间超过了 time.sleep(60),我无法按住 'enter' 关闭程序
    • 谢谢兄弟,我有个好主意^^
    猜你喜欢
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多