英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论