0

I have the following very simple code

stdout.write("Hello World")
stdout.write("\rBye world")
stdout.write("\rActually hello back")

Which prints as expected 'Actually hello back' however if i were to add a newline

stdout.write("\n")

How can I go back a newline and then to the beginning of the line so I can actually just output "Hi" instead of

Actually hello back
Hi

I tried

stdout.write("\r")
stdout.write("\b")

However none of them seem to do the trick. The end goal is to display a big chunk of text and then update the output in real time without having to write again. How can I achieve this in python?

EDIT My question is different than the one suggested as I don't want to modify a single line. I want to be able to print 4-5 lines of text and then replace them in real time instead of just one line that is modified.

Bula
  • 2,398
  • 5
  • 28
  • 54

1 Answers1

0

Well, if You want to gain full control over the terminal, I would suggest to use the curses library.

The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.

Using it, You can edit multiple lines in terminal like this:

import curses
import time

stdscr = curses.initscr()

stdscr.addstr("line 1\n")
stdscr.addstr("line 2\n")
stdscr.refresh()
time.sleep(3)

stdscr.erase()
stdscr.addstr("edited line 1\n")
stdscr.addstr("edited line 2\n")
stdscr.refresh()
time.sleep(3)

curses.endwin()

The capabilities of this library are much greater though. Full tutorial here.

Tony Babarino
  • 3,355
  • 4
  • 32
  • 44