Dynamic terminal printing with python
The simplest way, if you only ever need to update a single line (for instance, creating a progress bar), is to use '\r'
(carriage return) and sys.stdout
:
import sys
import time
for i in range(10):
sys.stdout.write("\r{0}>".format("="*i))
sys.stdout.flush()
time.sleep(0.5)
If you need a proper console UI that support moving the pointer etc., use the curses
module from the standard library:
import time
import curses
def pbar(window):
for i in range(10):
window.addstr(10, 10, "[" + ("=" * i) + ">" + (" " * (10 - i )) + "]")
window.refresh()
time.sleep(0.5)
curses.wrapper(pbar)
It's highly advisable to use the curses.wrapper
function to call your main function, it will take care of cleaning up the terminal in case of an error, so it won't be in an unusable state afterwards.
If you create a more complex UI, you can create multiple windows for different parts of the screen, text input boxes and mouse support.
How can I print a dynamic text in terminal using Python?
Yes you can!
Please refer to the answer found here
The code has been modified a little to look more like you want, and to use the more recent string formatting.
from time import sleep
import sys
for i in range(10):
sys.stdout.write("\rTime remaining: {} Seconds".format(i))
sys.stdout.flush()
sleep(1)
print '\n'
Print out text with dynamic pieces in Python to the Terminal
By default, print
outputs \n
(or \r\n
on Windows) at the end of the line to move to the New line. You just need to output \r
instead in order to Return to the beginning of the current line (and sleep for a second before outputting again at the same line):
import time, datetime
while True:
s = datetime.datetime.now().strftime('[ Time: %Y-%m-%d %H:%M:%S ]')
print(s, end='\r')
time.sleep(1)
Display text in terminal that is update-able with function
It's pretty easy to roll your own if you're only working with a single line. Chr(8)
(backspace) moves the cursor back a space. Keep track of how many characters you have printed on a line, don't print a newline at the end, and print enough backspaces to get back to where you want to be to print the new text. If the new text is shorter that what's already there, print enough spaces to erase the extra. The only real trick is to make sure you flush output, otherwise it won't show up until you print a newline. (As of Python 3.3 there's a flush
parameter on the print()
function, which makes that easy.)
Here's a little demo... I was aiming to make Line
something resembling an API for this, but don't really have the time to do it properly. Still, maybe you can take it from here...
import time
from io import StringIO
class Line():
def __init__(self):
self.value = ""
def __call__(self, *args, start=0, sep=" "):
chars = 0
io = StringIO()
print(*args, file=io, end="", sep=sep)
text = io.getvalue()
self.value = (self.value[:start] + " " * (start - len(self.value))
+ text + self.value[start + len(text):])
print(self.value, chr(8) * len(self.value), sep="", end="", flush=True)
def __next__(self):
self.value = ""
print()
def greet():
line = Line()
line("hello", start=2)
time.sleep(1)
line("world", start=8)
time.sleep(1)
line("hi ", start=2)
time.sleep(1)
line("world ", start=7)
time.sleep(0.3)
line("world ", start=6)
time.sleep(0.3)
line("world ", start=5)
time.sleep(1)
line("globe", start=5)
time.sleep(1)
for _ in range(4):
for c in "! ":
line(c, start=10)
time.sleep(0.3)
line("!", start=10)
time.sleep(1)
next(line)
greet()
Print in one line dynamically
Change print item
to:
print item,
in Python 2.7print(item, end=" ")
in Python 3
If you want to print the data dynamically use following syntax:
print(item, sep=' ', end='', flush=True)
in Python 3
Related Topics
Getting One Value from a Tuple
How to Extract an Arbitrary Line of Values from a Numpy Array
How to Solve Readtimeouterror: Httpsconnectionpool(Host='Pypi.Python.Org', Port=443) with Pip
How to Prevent Python's Urllib(2) from Following a Redirect
Run Child Processes as Different User from a Long Running Python Process
How to Set the Absolute Position of Figure Windows with Matplotlib
Python Dictionary Keys. "In" Complexity
How to Plot Nan Values as a Special Color with Imshow in Matplotlib
Pyserial Non-Blocking Read Loop
Duplicate Log Output When Using Python Logging Module
Python: Platform Independent Way to Modify Path Environment Variable
Implement Matlab's Im2Col 'Sliding' in Python
How to Filter Pandas Dataframes by Multiple Columns
What's the Difference Between _Builtin_ and _Builtins_