Print formatting

Python has options to reset the cursor position and flush output to prevent output from scrolling in the console e.g.

print("\r this will be over written by the next line",flush=true) 

Is there something similar in julia?

Try it and see:

julia> print("Over"); print("\rand over"); print("\rAgain....")
Again....
5 Likes

As for the flushing, see flush().

1 Like

There are two different concepts here that from your question it sounds like you’re conflating.

  1. Flushing: A program generates a stream of bytes that is consumed by the terminal and rendered. For efficiency programs don’t usually write to that stream byte-by-byte, they write to it in chunks. So as the program fills up a chunk, you don’t see anything on the screen, and then when the chunk is “flushed” to the stream then you all of a sudden see whatever data was in that chunk. In an interactive context it’s common to flush the buffer every time there is a newline character, so as a user you see the content line-by-line. The end result of what gets displayed on screen is independent of how big the chunks were, it just affects how often the screen updates.
  2. Carriage Return and Newline: In the old days terminals were physical teletype machines (think a remote-controlled typewriter) so it’s helpful to consider terminal control characters in that context. The Carriage Return character '\r' moved the carriage (the part that printed the letters) back to the beginning of the line. The Newline character '\n' moved the carriage down to the next line (fn1). So if you print the ‘\r’ character, it tells the terminal to move the cursor to the beginning of the line, so then the characters you print start overwriting what’s there. This behavior isn’t specific to Python or Julia, it’s a feature of the terminal (fn2). You can see this also if you print fewer characters than what’s already in the line:
print("Teletype\r"); for _ in 1:8; sleep(0.25); print("-") end

Footnotes

  • fn1: That’s why windows line endings use both characters (to both move the carriage to the beginning of the next line (I don’t know what the history is that led to windows and unix having different conventions).
  • fn2: Maybe there are other languages that represent the control characters differently, but this seems pretty standard
5 Likes

This is awesome in a REPL, thanks! Could this also be done in a Jupyter notebook?