How do I write output in same place on the console?
You can also use the carriage return:
sys.stdout.write("Download progress: %d%% \r" % (progress) )
sys.stdout.flush()
Write output in the same place in the console
The "magic" in the Python answer isn't unique to Python… it's just the \r
character: it resets the cursor position to the beginning of the line (without creating a new line). Subsequent print instructions will just overwrite the previous text if your terminal supports such cursor movements.
In Julia:
print("Download progress: $(progress)% \r")
flush(stdout)
You can also take a look at ProgressMeter.jl for fancier cursor movements and output.
Write output in same line, clearing previous line completely on python console
This none printable character \x1b[2K erase current line and fixed the problem.
import time
filename = 'file-name.txt'
for i in range(0, 101):
time.sleep(0.1)
print('Downloading File %s [%d%%]\r'% (filename, i), end="", flush=True)
print('\x1b[2K', end="")
print('Done...\r\n', end="", flush=True)
Write to same location in a console window with java
With Java 6 you can use the Console
to do something like this:
class Main {
public static void main(String[] args) throws InterruptedException {
String[] spinner = new String[] {"\u0008/", "\u0008-", "\u0008\\", "\u0008|" };
Console console = System.console();
console.printf("|");
for (int i = 0; i < 1000; i++) {
Thread.sleep(150);
console.printf("%s", spinner[i % spinner.length]);
}
}
}
\u0008
is the special backspace character. Printing that erases the last character on the line. By starting to print a |
and then prepending the \u0008
before all other characters you get the spinner behavior.
Note that this might not be 100% compatible with all consoles (and that System.console()
can return null
).
Also note that you don't necessarily have to use the console class, as printing this sequence to standard output commonly works just as well.
Print on the same spot in IPython console
I wrote this before the edit with IPython console, so I am not sure if this is a solution that works there or not, but here it its:
Instead of using the print() command, i would instead try to use sys.stdout.
This is a "progressreport" that I have in one of my scripts:
from sys import stdout
from time import sleep
jobLen = 100
progressReport = 0
while progressReport < jobLen:
progressReport += 1
stdout.write("\r[%s/%s]" % (progressReport, jobLen))
stdout.flush()
sleep(0.1)
stdout.write("\n")
stdout.flush()
The sleep function is just so that you can see the progresReport get larger. The "\r" part of the stdout is what makes the script "replace" the previus string. The flush() is added after the write() function, because it is sometimes needed to show the output on some enviroments.
Once you don't want to write to that row anymore, then you terminate it either by writing an empty string without "\r" or by writing a "\n".
Writing string at the same position using Console.Write in C# 2.0
Use Console.SetCursorPosition to set the position. If you need to determine it first, use the Console.CursorLeft and Console.CursorTop properties.
Print to same line in console, over previous text, Python 3.6
Perhaps, you want a time.sleep(1)
to have a better visualization, using stdout.write
:
import sys
import time
for i in range(5):
sys.stdout.write('\r' + str(i))
time.sleep(1)
OUTPUT:
Output to the same line overwriting previous output?
Here's code for Python 3.x:
print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r')
The end=
keyword is what does the work here -- by default, print()
ends in a newline (\n
) character, but this can be replaced with a different string. In this case, ending the line with a carriage return instead returns the cursor to the start of the current line. Thus, there's no need to import the sys
module for this sort of simple usage. print()
actually has a number of keyword arguments which can be used to greatly simplify code.
To use the same code on Python 2.6+, put the following line at the top of the file:
from __future__ import print_function
Related Topics
Running a Linux Command from Python
Shutting Down Computer (Linux) Using Python
Popen.Communicate() Throws Oserror: "[Errno 10] No Child Processes"
How to Search Directories and Find Files That Match Regex
How to Dereference Variable Id'S
Pandas Add Column to Groupby Dataframe
Pickled File Won't Load on MAC/Linux
Python: Get Output of the Shell Command 'History'
Extract Text from Xml Documents in Python
Calling Java/Scala Function from a Task
Dictionaries and Default Values
How to Directly Send a Python Output to Clipboard
How to Keep Track of Class Instances
Python List Doesn't Reflect Variable Change
Pelican 3.3 Pelican-Quickstart Error "Valueerror: Unknown Locale: Utf-8"
How to Run a Python Program in the Command Prompt in Windows 7