I'm writing a multithreaded program with an interactive console:
def console()
import readline
while True:
data = input()
do_whatever(data.split())
However, a library I'm using runs my callbacks from a different thread. The callback needs to print to the console. Thus I want to clear the command line, re-display the prompt, and re-show the command line.
How do I do that, short of re-implementing readline?
Starting from this answer that solves the issue for C, I arrived at the following Python code, which works well enough for my purposes:
import os
import readline
import signal
import sys
import time
import threading
print_lock = threading.Lock()
def print_safely(text):
with print_lock:
sys.stdout.write(f'\r\x1b[K{text}\n')
os.kill(os.getpid(), signal.SIGWINCH)
def background_thread():
while True:
time.sleep(0.5)
print_safely('x')
threading.Thread(target=background_thread, daemon=True).start()
while True:
try:
inp = input(f'> ')
with print_lock:
print(repr(inp))
except (KeyboardInterrupt, EOFError):
print('')
break
print_safely
\r\x1b[K (CR + CSI code EL) to remove the existing Readline promptPossible remaining issues:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With