Last active
October 20, 2024 14:14
-
-
Save ludndev/9174871c943ebc12c1b918db1b480c6a to your computer and use it in GitHub Desktop.
Same Line Print in Python using carriage return "\r" character
This file contains hidden or 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
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