Write and delete text in python terminal

Asked

Viewed 160 times

2

I’m doing an experiment in Python 3.6.2 which is a terminal counter, but I want to display the count always in the same position. I tried to insert the string using the function print and then delete the same text and rewrite the replacement text.

First I did the experiment without the time count.

text = ''
for i in range(10):
    text += '{} - '.format(i)

print(text, end='')
print('\b\b\b', end='', flush=True)

Note that after the loop the string text ends with ' - ', however the idea is to use the dash only to separate the numbers, then put three characters of Backspace to delete these characters, the final output of the program looks like this:

0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9

Now I made a new program with a wait of a second between a display and the other using the function Sleep module team.

from time import sleep

for i in range(10):
    line = str(i)
    print(line, end='', flush=True)
    sleep(1)
    print('\b' * len(line), end='', flush=True)

I hoped the values of i They appear in the terminal and then they’re erased so the next one can appear in the same place. But instead I got each value appearing on a new line, and I removed the default end character from the function print using the parameter end. Follow the exit:

0
1
2
3
4
5
6
7
8
9

After all, how do I get the numbers to appear in the same place?

  • Is that so? https://answall.com/q/207887/5878

  • Exactly what I needed, however I test here and this solution and it didn’t work, so I went to run the script through the terminal and found that the problem occurred because of Pycharm, the terminal works normal, both this solution you put as my own. Thank you very much.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.