Python显示时钟示例刷新数据

Python显示时钟示例刷新数据,python,curses,Python,Curses,此代码工作一次,显示当前日期时间并等待用户输入“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

此代码工作一次,显示当前日期时间并等待用户输入“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)

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

基本上,您希望的是无阻塞
getch
,延迟1秒。因此,您可以使用
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)
最佳实践使用。问题中的格式很奇怪,但使用它可以给出以下解决方案:

#!/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)
无论哪种方式,这里使用的超时限制了在脚本中花费的时间,并允许用户“立即”(在十分之一秒内)退出