You didn't say which OS you're using, so I'll assume that you're using a system with a standard ANSI/VT100 terminal, so we can use ANSI escape sequences to move the cursor, etc. If you're using a non-standard OS these sequences may not work in your terminal.
This program displays the number of seconds since the program was launched, at the top of the terminal window. The time display is updated every 0.1 seconds. Beneath the time display there's an input
prompt, which waits for the user to close the program.
from time import perf_counter
from threading import Timer
# Some ANSI/VT100 Terminal Control Escape Sequences
CSI = '\x1b['
CLEAR = CSI + '2J'
CLEAR_LINE = CSI + '2K'
SAVE_CURSOR = CSI + 's'
UNSAVE_CURSOR = CSI + 'u'
GOTO_LINE = CSI + '%d;0H'
def emit(*args):
print(*args, sep='', end='', flush=True)
start_time = perf_counter()
def time_since_start():
return '{:.6f}'.format(perf_counter() - start_time)
def show_time(interval):
global timer
emit(SAVE_CURSOR, GOTO_LINE % 1, CLEAR_LINE, time_since_start(), UNSAVE_CURSOR)
timer = Timer(interval, show_time, (interval,))
timer.start()
# Set up scrolling, leaving the top line fixed
emit(CLEAR, CSI + '2;r', GOTO_LINE % 2)
# Start the timer loop
show_time(interval=0.1)
input('Press Enter to stop the timer:')
timer.cancel()
# Cancel scrolling
emit('\n', SAVE_CURSOR, CSI + '0;0r', UNSAVE_CURSOR)
This code was derived from this previous answer of mine.
Here's a more primitive version, with no cursor control, apart from using the '\r'
Carriage Return control character, which should work on any system. You probably don't need the flush=True
arg to print
, depending on your terminal.
from time import time as perf_counter
from threading import Timer
start_time = perf_counter()
def show_time(interval):
global timer
print(' {:.6f}'.format(perf_counter() - start_time), end='\r', flush=True)
timer = Timer(interval, show_time, (interval,))
timer.start()
# Start the timer loop
show_time(interval=0.1)
input(15 * ' ' + ': Press Enter to stop the timer.\r')
timer.cancel()