Python诅咒显示时钟示例刷新数据



此代码工作一次,显示当前日期时间并等待用户输入'q'退出:

#!/usr/bin/python
import curses
import datetime
import traceback
from curses import wrapper
def schermo(scr, *args):
try:
stdscr = curses.initscr()
stdscr.clear()
curses.cbreak()
stdscr.addstr(3, 2, f'{datetime.datetime.now()}',  curses.A_NORMAL)
while True:
ch = stdscr.getch()
if ch == ord('q'):
break
stdscr.refresh()
except:
traceback.print_exc()
finally:
curses.echo()
curses.nocbreak()
curses.endwin()

curses.wrapper(schermo)

让屏幕上的数据每秒都发生变化的最佳做法是什么?

最佳实践使用timeout。问题中的格式很奇怪,但使用它可以给出这样的解决方案:

#!/usr/bin/python
import curses
import datetime
import traceback
from curses import wrapper
import time
def schermo(scr, *args):
try:
ch = ''
stdscr = curses.initscr()
curses.cbreak()
stdscr.timeout(100)
while ch != ord('q'):
stdscr.addstr(3, 2, f'{datetime.datetime.now()}',  curses.A_NORMAL)
stdscr.clrtobot()
ch = stdscr.getch()
except:
traceback.print_exc()
finally:
curses.endwin()
curses.wrapper(schermo)

然而,这个问题要求每秒更新一次。这是通过更改格式来完成的:

#!/usr/bin/python
import curses
import datetime
import traceback
from curses import wrapper
import time
def schermo(scr, *args):
try:
ch = ''
stdscr = curses.initscr()
curses.cbreak()
stdscr.timeout(100)
while ch != ord('q'):
stdscr.addstr(3, 2, f'{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}',  curses.A_NORMAL)
stdscr.clrtobot()
ch = stdscr.getch()
except:
traceback.print_exc()
finally:
curses.endwin()
curses.wrapper(schermo)

无论哪种方式,这里使用的超时限制了在脚本中花费的时间,并允许用户退出";立即";(在十分之一秒内(。

基本上,您似乎想要的是延迟1秒的无阻塞getch。因此,您可以使用nodelay选项来设置非阻塞getch,并使用time库来设置延迟。示例代码如下:

#!/usr/bin/python
import curses
import datetime
import traceback
from curses import wrapper
import time
def schermo(scr, *args):
try:
ch = ''
while ch != ord('q'):
stdscr = curses.initscr()
stdscr.clear()
stdscr.nodelay(1)
curses.cbreak()
stdscr.erase()
stdscr.addstr(3, 2, f'{datetime.datetime.now()}',  curses.A_NORMAL)
ch = stdscr.getch()
stdscr.refresh()
time.sleep(1)
except:
traceback.print_exc()
finally:
curses.echo()
curses.nocbreak()
curses.endwin()

curses.wrapper(schermo)

最新更新