python - 如何在python中等待用户输入5秒

标签 python keyboard

我正在尝试处理文件的内容。我需要关于如何与他人互动的想法 用户并等待按下某个键将当前行写入另一个文件。预先感谢您。

with open(srcFile) as f:
    line = f.readline().strip()    
    #- do something with line

    #- part where I need help
    if s is press, write the current line to file
    if s is not pressed after 5 seconds, continue with the next line in srcFile

最佳答案

对于这种情况,您可以使用 timekeyboard 包:

import time
import keyboard

start_time = time.time()  # Start the timer
key_pressed = False

while True:
    if keyboard.is_pressed("s"):
        key_pressed = True
        break

    if time.time() - start_time >= 5:
        break

if key_pressed:
    # write the current line to file

您可以使用上面的代码进行测试,看看效果。

关于python - 如何在python中等待用户输入5秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77063818/

相关文章:

python - 在 Flask 的 WTforms 中创建动态字段

python - 在 python 中定义 @classmethod lambda

python - Pandas:如何创建运行计数列?

ios - 子类化 UIView 时如何检测箭头键?

python - 在 python/pygame 中使用箭头键使图像移动一格

python - django Models.py 的问题

python - 类型错误 : not all arguments converted during string formatting python 3

java - Double 的 JFormattedTextField 仍然需要字符

c - 全局按键监听器

Javascript:Keydown 事件: "Up"箭头键阻止进一步的箭头键 Keydown 事件? (回答:键盘重影)