6

The \b control character, as I understand it, is not supposed to erase the previous character (this would be \b + a del character as well), so something like this works:

>>> print 'pototo\b\b\ba'
potato

Is there a character for moving forwards, like a non-overwriting space? Expected usage would be something like (I've called this character \x):

>>> print 'pototo\r\x\x\xa'
potato

Obviously on a typewriter a normal space would do this just fine. But on a terminal a space erases the letter underneath.

My use case is a pexpect matching kind of scenario where I want to retrospectively go back and decorate certain parts of the output of a character stream with colours, and I'm wondering whether keeping a cache of the whole current line in memory will be necessary or not.

wim
  • 338,267
  • 99
  • 616
  • 750
  • 1
    It doesn't look like there is any way to move forwards in [python's "escape sequence tokens"](http://docs.python.org/2/reference/lexical_analysis.html#grammar-token-escapeseq)... – Andy Hayden Dec 10 '12 at 11:05
  • I don't believe there is such a character, at least an exhaustive search didn't reveal any. However, under linux you should be able to explicitly set the cursor position using the [curses module](http://docs.python.org/2/library/curses.html). – primo Dec 10 '12 at 11:11

2 Answers2

3

If you can rely on ANSI escape code sequences in your terminal (*), you can use the Cursor Forward (CUF) sequence "CSI n C", like this:

print "Pototo\b\b\ba\x1b[2Ces"

and get:

Potatoes

CSI is \x1b[, and is used to start ANSI escape code sequences. 2 is the number of characters to move to the right, and C is the command to move rightwards.


(*) A good approximation is that you can rely on ANSI codes unless you need to support Windows.

Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
0

You should re-write the characters:

>>> print 'pototo\rpota'
potato

If you do not want to re-write them , than you ought to use a library like curses to manually set the cursor position.

Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
  • The problem with this is then you can't append anything to the end of the word (without overwriting). – Andy Hayden Dec 10 '12 at 12:49
  • @hayden My point is that command line was not written to allow these complex situations. You can completely rewrite a single line(as my answer points out) but trying to do anything else you will have not portable code. I'd advise you to use `curses` or an other library for terminal manipulation if you want to do such things. – Bakuriu Dec 10 '12 at 13:10
  • Sorry I did not properly read the second part of your answer. – Andy Hayden Dec 10 '12 at 13:17