python Realization of Text Progress Bar Program Progress Bar Loading Progress Bar Single Line Refresh Function

  • 2021-07-09 08:38:29
  • OfStack

python realizes the text progress bar program progress bar loading progress bar single line refresh function, the specific contents are as follows:

Use time library to replace the process of a program, do examples,

The idea is to simply print out the progress of the program

The single-line refresh key is\ r,

python defaults to line wrapping after print, so adding 1\ r is to roll back the cursor to the previous position


import time
tm=10
print('{:-^18}'.format(' Begin '))
for i in range(tm+1):
  a='#'*i
  b='.'*(tm-i)
  c=(i/tm)*100
  print('\r{:^3.0f}%[{}->{}]'.format(c,a,b),end="")# Remember to roll back the cursor , This is python3 The style of play, python2 To put the last one end= ' ' Just change it 
  time.sleep(0.1)# This is the emulator process, which can be set time.sleep Replace with program process 
print('{:-^18}'.format(' End '))

The effect of not having\ r is


-------- Begin --------
 0 %[->..........]
10 %[#->.........]
20 %[##->........]
30 %[###->.......]
40 %[####->......]
50 %[#####->.....]
60 %[######->....]
70 %[#######->...]
80 %[########->..]
90 %[#########->.]
100%[##########->]
-------- End --------

The final effect of having\ r is

---Beginning---
100%[##########- > ]--end--

The last two here overlap, so just add a new line, and the last line will be changed to,

print('\n'+'{:-^18}'.format('结束'))

ps: Let's take a look at using python to dynamically refresh the text progress bar in a single line

TextProBar.py


import time
scale = 50
print(" Start of execution ".center(scale // 2,"-"))
start = time.perf_counter()
for i in range(scale + 1):
  a = "*" * i
  b = "." * (scale - i)
  c = (i / scale) * 100
  dur = time.perf_counter() - start
  print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end = "")
  time.sleep(0.1)
print("\n"+" End of execution ".center(scale // 2,"-"))

\ r: You can bring the printed cursor back to the previous position to overwrite the previous characters, but it will be masked by IDLE. So you want to use the command line to ` execute
(IDLE itself is the development environment for writing programs, not the main environment for running programs. We either double-click or through the console for normal running programs, and rarely run directly through IDLE. Because IDLE is set as the development environment, in order to ensure the running effect of its parameters, one of the effects\ r is shielded)

Summarize


Related articles: