让 Python 脚本在 time.sleep 期间仍然接收输入。

huangapple go评论54阅读模式
英文:

Let python script still receive input while in time.sleep

问题

以下是您要翻译的代码部分:

要达到的目标是当我按下 `*` 键时程序应该在执行其他操作之前等待 17如果我不按任何键它可以继续每 11 秒按下 `]`问题在于如果我在任何 `time.sleep` 时间段内按下 `*`按键的操作将不会执行

```python
import pyautogui
import time
import keyboard

while not keyboard.is_pressed('*'):
    if keyboard.is_pressed('*'):
        time.sleep(17)
    else:
        time.sleep(11)
        pyautogui.press(']')

希望这有所帮助。

英文:

What I want to achieve here is that when I press * the program should wait for 17 seconds before doing anything else and if I don't press anything it can continue pressing the ] key every 11 seconds. The problem here is that if I were to press the * while we are in any time.sleep period, the press of the key will not go through.

   import pyautogui
   import time
   import keyboard
    
    
    
    while not keyboard.is_pressed('*'): 
        if keyboard.is_pressed('*'):
            time.sleep(17)
        else:
            time.sleep(11)
            pyautogui.press(']')

答案1

得分: 1

有很多方法可以完成这个任务。其中一个较简单(但绝不是最佳)的方法是以较短的间隔(比如0.1秒)休眠,以便周期性地唤醒并轮询键盘。您可以在一个变量中跟踪完成“等待”的系统时间点,然后在那一点上退出循环。

英文:

There are a lot of ways to accomplish this.

One of the simpler (but certainly not best) ways is to sleep in shorter increments (say 0.1 sec) to wake up periodically and poll the keyboard. You would track in a variable the system time at which point you are done "waiting" and break out of your loop at that point.

答案2

得分: 0

这对我有用

import pyautogui
import time
import keyboard

last_star_press = 0  # 初始化变量以跟踪上次*键按下的时间

while True:
    if keyboard.is_pressed('*'):
        last_star_press = time.time()  # 更新上次*键按下的时间
        time.sleep(17)
    else:
        if time.time() - last_star_press >= 11:
            pyautogui.press(']')
            last_star_press = time.time()  # 更新上次按键的时间
        time.sleep(1)  # 添加小延迟以减少CPU使用率
英文:

This works for me

import pyautogui
import time
import keyboard

last_star_press = 0  # initialize variable to keep track of time of last * press

while True:
    if keyboard.is_pressed('*'):
        last_star_press = time.time()  # update time of last * press
        time.sleep(17)
    else:
        if time.time() - last_star_press >= 11:
            pyautogui.press(']')
            last_star_press = time.time()  # update time of last key press
        time.sleep(1)  # add a small delay to reduce CPU usage

huangapple
  • 本文由 发表于 2023年2月16日 04:51:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定