Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can I use to go one line break back in a terminal in Python?

I can go one caracter back using \b :

>>> print("123#456")
123#456
>>> print("123#\b456")
123456

But it doesn't work if a line break is involved :

>>> print("123#\n456")
123#
456
>>> print("123#\n\b456")
123#
456

Is there a way to go line break back ?

I'm asking this because I have a progress at the previous line:

53%

And I use \b to update the value. But if somebody prints something, it breaks it. I tried to create a buffer of strings and print enought '\b' to compensate for it, then print the buffer back. But it doesn't work if there are line breaks.

like image 283
e-satis Avatar asked Aug 15 '13 07:08

e-satis


1 Answers

One possible (a bit hacky) solution is to use '\033[1A' to go back one line. Replace 1 with number of lines to jump back. There are several other escape sequences you can use to manipulate the cursor. Check out the complete list at: http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html

- Position the Cursor:
  \033[<L>;<C>H
     Or
  \033[<L>;<C>f
  puts the cursor at line L and column C.
- Move the cursor up N lines:
  \033[<N>A
- Move the cursor down N lines:
  \033[<N>B
- Move the cursor forward N columns:
  \033[<N>C
- Move the cursor backward N columns:
  \033[<N>D

- Clear the screen, move to (0,0):
  \033[2J
- Erase to end of line:
  \033[K

- Save cursor position:
  \033[s
- Restore cursor position:
  \033[u

Note that this will probably not work for all terminals.

like image 55
StianE Avatar answered Oct 21 '22 22:10

StianE