Last active
April 3, 2019 07:57
-
-
Save solesensei/05a97bbe8b75cd2368a8e6d5e00d6047 to your computer and use it in GitHub Desktop.
Python script which make you able to edit stdout printed text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment