Skip to content

Instantly share code, notes, and snippets.

@Leedehai
Created January 10, 2019 04:55
Show Gist options
  • Save Leedehai/7a000413b2e3554e0214c42343caa969 to your computer and use it in GitHub Desktop.
Save Leedehai/7a000413b2e3554e0214c42343caa969 to your computer and use it in GitHub Desktop.
Python: print strings in the same line, overwriting the previous content
#!/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