104

I would like to overwrite something on a line above in a serial console. Is there a character that allows me to move up?

6
  • 2
    Define "serial console". Is this some terminal emulation program running on a PC, if so which one? Jul 13, 2012 at 16:32
  • FWIW, the reason there's nothing in standard C++ is that it supports the possibility that the output genuinely is a serial console. Like a teletype machine or something. The standard doesn't indulge itself in frivolities like moving the cursor ;-) Jul 13, 2012 at 16:35
  • 1
    I am using PuTTY to monitor the com port.
    – Sponge Bob
    Jul 13, 2012 at 16:37
  • What platform are you running this on?
    – Levon
    Jul 13, 2012 at 16:41
  • 1
    FYI, the notes here might be helpful for someone interested in control sequence(notes.burke.libbey.me/ansi-escape-codes). But with the advent of colorama you might not need to learn that at all.
    – JP Zhang
    Mar 14, 2022 at 10:35

6 Answers 6

155

Most terminals understand ANSI escape codes. The relevant codes for this use case:

  • "\033[F" – move cursor to the beginning of the previous line
  • "\033[A" – move cursor up one line

Example (Python):

print("\033[FMy text overwriting the previous line.")
6
  • This did not work in PuTTY. But thank you, I am sure I will use this for other projects.
    – Sponge Bob
    Jul 13, 2012 at 16:37
  • 1
    @KeeganMcCarthy: This should actually work in PuTTY, but I accidentally missed a square bracket. Please try again. Jul 13, 2012 at 16:51
  • 1
    I re-read OPs question, you are right, the ANSI approach would be a better approach and sufficient here.
    – Levon
    Jul 13, 2012 at 17:49
  • 2
    You can use the colorama package to make the \033[A sequence work on Windows.
    – jtpereyda
    Oct 14, 2020 at 20:16
  • 1
    To make it work on windows using the standard library just run os.system("") Mar 5, 2022 at 0:39
11

No, not really easily, for that you'd have to use something like the curses library, especially if you want to have more control over cursor placement and do more things programatically.

Here's a link for the Python docs on Programming with Curses, and this short tutorial/example might be of interest too.

I just found this note in the docs in case you are using Windows:

No one has made a Windows port of the curses module. On a Windows platform, try the Console module written by Fredrik Lundh. The Console module provides cursor-addressable text output, plus full support for mouse and keyboard input, and is available from http://effbot.org/zone/console-index.htm.

I believe for C++ there is the NCurses library, the linked page has a section on moving the cursor if you want to poke around with C++. Also there's the NCurses Programming HowTo.

Long time ago I used the curses library with C quite successfully.

Update:

I missed the part about running this on a terminal/serially, for that the ANSI escape sequence, especially for a simple task like yours, will be easiest and I agree with @SvenMarnach solution for this.

4
  • 2
    I don't agree with "No, not really easily, for that you'd have to use somethink like the curses library". You can do cursor placement with ANSI escape codes, and they work on both Windows and POSIX, and they are easy. Jul 13, 2012 at 17:24
  • @SvenMarnach Hmm, ok, so noted. ANSI's been around for a long time, as as the curses library. I believe the curses lib provides a better programmatic interface (though it's been a while since I've used it) and will let you query various screen parameters .. but are you saying other than that there's no need for the curses library? (not trying to argue, just understand)
    – Levon
    Jul 13, 2012 at 17:29
  • The curses library is much more versatile, of course. And I would definitely use it for any textual user interface on POSIX operating systems. However, the OP wants to do some trivial task (moving the cursor up one line) on Windows. It seems overkill to use a library for this if you can use ANSI sequences, and in this case, the library does not even exist on Windows. Jul 13, 2012 at 17:33
  • @SvenMarnach Ah, ok, I see your point, thanks for clarifying. I thought the 2nd half of my first sentence somewhat qualified my statement, but I can see it's perhaps not explicit enough. I'm sure OP can select the solution that works best for them, it's good to have choices.
    – Levon
    Jul 13, 2012 at 17:35
3
for i in range(10):  
    print("Loading" + "." * i) 

    doSomeTimeConsumingProcessing()

    sys.stdout.write("\033[F") # Cursor up one lin

Try this in Python and replace doSomeTimeConsumingProcessing() with any routine needed, and hope it helps

1
  • 2
    If anyone wants to do this then just add the kwarg end='\r' to the print function like this: print('Loading', end='\r') Aug 25, 2018 at 17:38
2

Carriage return can be used to go to the beginning of line, and ANSI code ESC A ("\033[A") can bring you up a line. This works on Linux. It can work on Windows by using the colorama package to enable ANSI codes:

import time
import sys
import colorama

colorama.init()

print("Line 1")
time.sleep(1)
print("Line 2")
time.sleep(1)
print("Line 3 (no eol)", end="")
sys.stdout.flush()
time.sleep(1)
print("\rLine 3 the sequel")
time.sleep(1)
print("\033[ALine 3 the second sequel")
time.sleep(1)
print("\033[A\033[A\033[ALine 1 the sequel")
time.sleep(1)
print()  # skip two lines so that lines 2 and 3 don't get overwritten by the next console prompt
print()

Output:

> python3 multiline.py
Line 1 the sequel
Line 2
Line 3 the second sequel
>

Under the hood, colorama presumably enables Console Virtual Terminal Sequences using SetConsoleMode.

1
  • > It can work on Windows by using the colorama package to enable ANSI codes Or you can just do os.system(""). Nov 9, 2022 at 0:47
1

I may be wrong but :

#include <windows.h>


void gotoxy ( int column, int line )
{
  COORD coord;
  coord.X = column;
  coord.Y = line;
  SetConsoleCursorPosition(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    coord
    );
}

in windows standard console.

0

A simple way based on @Sven Marnach answer:

print(f'\033[A\rxxx')
  • \033[A: Move cursor one line up.
  • \r: Move the cursor to the beginning of the line.
  • xxx: The string to be printed. {xxx} if it is a variable

If you have some extra characters from the previous line after your string, overwrite them with white space, depending on the length of the previous line. Below I added 10 white spaces.

print(f'\033[A\rxxx{' '* 10}')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.