Python显示时钟示例刷新数据

2024-10-03 17:23:22 发布

您现在位置: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)

让屏幕上的数据每秒更改的最佳做法是什么


Tags: 代码用户fromimportdatetimebinusrdef
2条回答

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

#!/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)

相关问题 更多 >