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

问题描述 投票:0回答:1

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

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
python keyboard
1个回答
0
投票

您可以在这种情况下使用

time
keyboard
包:

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:
    print("hello")

你可以用上面的代码测试一下看看效果。

© www.soinside.com 2019 - 2024. All rights reserved.