Created
January 10, 2019 04:55
-
-
Save Leedehai/7a000413b2e3554e0214c42343caa969 to your computer and use it in GitHub Desktop.
Python: print strings in the same line, overwriting the previous content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Tested on Python2.7 and Python3.5 | |
import os, sys | |
import time | |
lines = [ | |
"abc", | |
"abcdefghi", | |
"a", | |
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", | |
]; | |
# width of terminal | |
cols = int(os.popen('stty size', 'r').read().split()[1]) | |
def to_width(s, width): | |
extra_space = width - len(s) | |
if extra_space >= 0: | |
return s + ' ' * extra_space | |
else: | |
return s[:width - 3] + "..." | |
for i in range(100): | |
sys.stdout.write("\r%s" % to_width(lines[i % len(lines)], cols - 20)) | |
sys.stdout.flush() | |
time.sleep(0.1) | |
sys.stdout.write("\n") | |
sys.stdout.flush() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment