+ 6

Python: replacing output lines?

I'd like to have a function that replaces a line in the output with another line, e.g.: from time import sleep print("Hello") sleep(5) replaceLine(1, "World") this would first put out "Hello", then after 5 seconds replace line 1 (which is the "Hello" one) with the string "World". Is there any built-in function or module that you can use for this?

8th Apr 2017, 2:48 PM
Supersebi3
Supersebi3 - avatar
9 Answers
+ 9
print("\33[2J") # clear the screen print("\33[1A") # move the cursor up one line # The CSI is '\33[' ;)
8th Apr 2017, 5:38 PM
visph
visph - avatar
+ 9
You need to use ansi escape code ( or a module to handle them more friendly ^^ ): - https://en.m.wikipedia.org/wiki/ANSI_escape_code - https://pypi.python.org/pypi/blessings - https://pypi.python.org/pypi/colorama [ edit ] Unfortunatly, this doesn't work in Sololearn terminal output emulator ^^
8th Apr 2017, 5:20 PM
visph
visph - avatar
+ 8
""" You need to write something immediatly after the command to move cursor up, as by default print() function add a new line char ( so cursor move one line down, as he doesnt have move ), or move up 2 lines instead of 1 to anihilate the new line added by the print function ( you can also specify an empty ending char at parameter of the print() function )... """ # So: print("Attempt") print("\33[1A") # is equivalent to: print("Attempt") print("\33[2A") print('Test")
8th Apr 2017, 5:47 PM
visph
visph - avatar
+ 6
@visph - nice answers, using terminal escapes.
13th Apr 2017, 1:13 AM
Kirk Schafer
Kirk Schafer - avatar
+ 5
@visph works perfectly, thanks!
8th Apr 2017, 7:20 PM
Supersebi3
Supersebi3 - avatar
+ 4
I want to do it in the console (console application)
8th Apr 2017, 3:22 PM
Supersebi3
Supersebi3 - avatar
+ 4
@visph I read that wikipedia article, but how do I use those codes in python?
8th Apr 2017, 5:33 PM
Supersebi3
Supersebi3 - avatar
+ 1
It depends where you want it to do its stuff. In console applications, it might be feasable, on GUI it's relatively easily. In the shell, don't even try, I think it's impossible
8th Apr 2017, 3:14 PM
Amaras A
Amaras A - avatar
+ 1
Then I don't really know how to do it
8th Apr 2017, 3:23 PM
Amaras A
Amaras A - avatar