This code work once, show current datetime and wait user input 'q' to quit:
#!/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)
What is the best practice to make data on the screen change each second?
Best practice uses timeout
. The format in the question is odd, but using that gives this solution:
#!/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)
However, the question asked for updating once per second. That's done by changing the format:
#!/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)
Either way, the timeout used here limits the time spent in the script, and allows the user to quit "immediately" (within a tenth of a second).