move cursor in python code example
Example: move cursor in python
import sys
def write(string: str, flush: bool=True) -> None:
sys.stdout.write(string)
if flush:
sys.stdout.flush()
# up: \x1b[{n}A
# down: \x1b[{n}B
# right: \x1b[{n}C
# left: \x1b[{n}D
# have you noticed that in python when you hit use the arrow
# keys in an input, you get this weird output?
# ^[[A
# ^[[B
# ^[[C
# ^[[D
# now you'll understand why. when you type something an input,
# it literally just prints out everything you type. if you type
# a newline character though, it will return the text from the
# input stream to the program. when you type a "move up", "move down",
# or etc character, the function knows that the character is not
# a newline character, so it just writes it to the console. this
# is why you see stuff like ^[[A when you use the arrow keys on
# your keyboard when typing in the input function
write('type ur name below\n\nhit enter when you\'re done')
# we will read the user's name from the input stream in between
# the two newlines
write('\x1b[1A') # move up one space
write('\x1b[26D') # move left 26 spaces
name = sys.stdin.readline() # read the user's name
write('\x1b[1B') # move down 1 space
write(name) # write the user's name to the console output