I have a Python program I am writing and I want it to be able to change text after it is printed. For example, let\'s say I want to print \"hello\" and erase one letter eve
You could use dynamical stdout with getch() characters and loop
Example: https://asciinema.org/a/238478
Code:
# Script make you able to edit printed text
# stdin and stdout at the same time
# https://asciinema.org/a/238478
# https://gist.github.com/SoleSensei/05a97bbe8b75cd2368a8e6d5e00d6047
import sys
from getch import getch
def flush_append(char):
# just append char to the end
sys.stdout.write(char)
sys.stdout.flush()
def flush_write(line):
# clear all and rewrite line
sys.stdout.write(f"\r{' '*100}\r")
sys.stdout.flush()
sys.stdout.write(line)
sys.stdout.flush()
def interactive_input(line):
flush_write(line)
c = getch()
while ord(c) not in (13, 3): # 13 - Enter, 3 - Ctrl+C
if ord(c) in (127, 8): # 127,8 - Backspace (Unix, Windows)
line = line[:-1]
flush_write(line)
else:
# decode to string if byte
c = c.decode('ascii') if str(c)[0] == 'b' else c
line += c
flush_append(c)
c = getch()
print() # add EOL
return line
s = interactive_input('stdout editable line')