Skip to content

Instantly share code, notes, and snippets.

@ludndev
Last active October 20, 2024 14:14
Show Gist options
  • Save ludndev/9174871c943ebc12c1b918db1b480c6a to your computer and use it in GitHub Desktop.
Save ludndev/9174871c943ebc12c1b918db1b480c6a to your computer and use it in GitHub Desktop.
Same Line Print in Python using carriage return "\r" character
from time import sleep
from math import ceil
from os import get_terminal_size
def main():
for i in range(100):
sleep(0.1)
print(f'\r{str(ceil(i/100*100)).strip()} % complete', end='')
print(f'\r{' ' * get_terminal_size().columns}', end='') # clear the line before displaying the next line
print('\r100% complete', end="\n")
try:
main()
except KeyboardInterrupt:
print("Exiting...")
exit(0)
except Exception as e:
print(f"An error occurred: {e}")
finally:
print("Goodbye!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment