2

Is there a combination of VT100 escape sequences that will allow my C program to print something like:

Waiting......

to a console, in such a way that the dots appear one by one? Essentially, I want a command that will let me insert an extra '.' in front of a newline that has already been sent.

I'm looking for a quick one-liner for linux; it does not have to be portable. ncurses is overkill for this.

Andrew Wagner
  • 22,677
  • 21
  • 86
  • 100
  • You can't *quite* undo the effect of a newline unless you happen to know how long the previous line was; the terminal can move the cursor up one line, but doesn't know how far forward to move it. – Keith Thompson Oct 12 '11 at 00:36
  • 3
    Have you considered simply not outputting the newline? Easy peasy. – Hans Passant Oct 12 '11 at 00:44

2 Answers2

2

you can add ESC[K (clear to end of line) to ESC[A (up one line), and print your new line text

an example using Python:

import random, time
for _ in range(100):
    print('\x1b[A\x1b[Kthis will print each line cleanly: %d' %(random.randint(0, 100000)))
    time.sleep(0.1)

if you really want to be neat about things, use ESC7 (save cursor) and ESC8 (restore cursor)

then, you write your line and at the end of it you use ESC7. at the beginning of the print statement, you use ESC8. note, unless you turn off automatic newlines, this will not work at the bottom of your tty. it will work on all lines but the bottom.

import random, time

print('this will print each dot cleanly: \x1b7')
for _ in range(10):
    print('\x1b8.\x1b7')
    print('print more foo: %d' %_)
    time.sleep(0.1)

for shell scripting (bash), you would use printf "..." without a \n, or echo -n

FirefighterBlu3
  • 399
  • 5
  • 11
1

An easy way to do this is to use the escape sequence

"\x1b[A"

to move the cursor up one line. Then, re-print the "Waiting..." message, with one more dot than the last time.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285