python - 在python中等待输入1秒
问题描述
我正在尝试使用 curses 在 Python 中制作一个笔记应用程序。左下角应该是一个每秒更新的时钟。
我现在遇到的问题是它要么必须休眠 1 秒,要么等待输入。
如果没有注册输入,是否可以等待输入 1 秒并继续?
我想这样做的原因是为了防止在应用程序中移动时出现延迟。
我在想像多线程这样的东西可以完成这项工作,但也有一些问题。
这是我到目前为止的代码:
#!/usr/bin/env python3
import curses
import os
import time
import datetime
import threading
def updateclock(stdscr):
while True:
height, width = stdscr.getmaxyx()
statusbarstr = datetime.datetime.now().strftime(' %A')[:4] + datetime.datetime.now().strftime(' %Y-%m-%d | %H:%M:%S')
stdscr.addstr(height-1, 0, statusbarstr)
time.sleep(1)
def draw_menu(stdscr):
k = 0
stdscr.clear()
stdscr.refresh()
threading.Thread(target=updateclock, args=stdscr).start()
cursor_y = 0
cursor_x = 0
while (k != ord('q')):
#while True:
stdscr.clear()
height, width = stdscr.getmaxyx()
stdscr.addstr(height//2, width//2, "Some text in the middle")
if k == curses.KEY_DOWN:
cursor_y = cursor_y + 1
elif k == curses.KEY_UP:
cursor_y = cursor_y - 1
elif k == curses.KEY_RIGHT:
cursor_x = cursor_x + 1
elif k == curses.KEY_LEFT:
cursor_x = cursor_x - 1
stdscr.refresh()
#time.sleep(1)
# Wait for next input
k = stdscr.getch()
curses.wrapper(draw_menu)
代码看起来很乱,这是我第一次主要关注 curses 函数。
是否可以只等待输入k = stdscr.getch()
1 秒?
解决方案
默认情况下,getch 将阻塞,直到您准备好字符输入。如果 nodelay 模式为 True,那么您将获得准备好的字符的字符值 (0-255),或者您将获得 -1 表示没有准备好字符值。
stdscr.nodelay(True) #Set nodelay to be True, it won't block anymore
k = stdscr.getch() #Either the next character of input, or -1
推荐阅读
- http - NiFi:GetHTTP处理器正则表达式无效错误
- node.js - 如何处理表单动作的响应?
- flutter - 相同的代码,两种不同的结果 | 在颤动中导航到另一条路线
- sql - 使用两个 AS 变量调用 table 并在 table 只有一行数据时比较它们
- python - 记录时出现多条消息
- javascript - AJAX 请求向用户显示内容但不在页面源上
- prolog - 从带有数字和字符串的列表中查找最小值
- bash - 如何在带有固定参数的 shell 脚本中运行 shell 脚本
- javascript - 从新打开的窗口(弹出窗口)访问 facebook like 按钮
- javascript - 将流视频从视频标签播放到画布