Progress bar in the python Console

Source: Internet
Author: User
This article mainly introduces how to implement the progress bar function in the python console, if you want to know, you can refer to the fact that most of us want to write some simple python scripts and want to be able to implement the progress bar during the program running process to view the program running speed or progress. I will discuss this question with you today: how to implement progress bars in the python Console

The main problem with the progress bar is that all characters are in the same line and can be modified.

However, when the print statement is executed, python will add '\ n' at the end of the statement while printing the statement, that is, line feed, as a result, Once printed in the console, it cannot be modified. Therefore, print cannot be used for output.

We want to use the sys. stdout. write () function, which outputs the string in the console without adding any end, which means that the output is not completely complete. You can use the sys. stdout. flush () function to temporarily print the output on the console (this is the illusion of print. Let's call this fake output first ). So if we use the Escape Character '\ R' (back to the beginning of the line), is everything reasonable?

That is to say, when printing a string, '\ n' is not added, and the cursor is directed back to the beginning of the line, and the current buffer is displayed, as if it were print, however, the cursor is still in the original position.

For example:

import sys, timefor i in range(5): sys.stdout.write('{0}/5\r'.format(i + 1)) sys.stdout.flush() time.sleep(1)

Execute this code in the terminal to get a simple progress bar.

Next, we need to solve two problems:

I. Clear the Buffer Zone

Some smart readers may find that problems may occur when new strings are shorter than before, such as the following code:

import sys, timefor i in range(5): sys.stdout.write(str(i) * (5 - i) + '\r') sys.stdout.flush() time.sleep(1)

The running results are different from what we hope.

In fact, the characters that have been flushed out are not automatically cleared, so only newly written characters are modified. In view of this, my current solution is to first output a wave of spaces to overwrite the previous string and then re-write:

import sys, timefor i in range(5): sys.stdout.write(' ' * 10 + '\r') sys.stdout.flush() sys.stdout.write(str(i) * (5 - i) + '\r') sys.stdout.flush() time.sleep(1)

2. fixed bottom side output

Sometimes we want to have some other output while loading the progress bar.

We may wish to output the desired output string after refreshing the previous output, and then output the progress bar on the false.

Use the following code:

import sys, timefor i in range(5): sys.stdout.write(' ' * 10 + '\r') sys.stdout.flush() print i sys.stdout.write(str(i) * (5 - i) + '\r') sys.stdout.flush() time.sleep(1)

You can complete the required tasks.

How is it, in fact, the principle is quite simple?

Here is a self-implemented class used to print the progress bar:

# -*- coding:utf-8 -*-# Copyright: Lustralisk# Author: Cedric Liu# Date: 2015-11-08import sys, timeclass ProgressBar: def __init__(self, count = 0, total = 0, width = 50):  self.count = count  self.total = total  self.width = width def move(self):  self.count += 1 def log(self, s):  sys.stdout.write(' ' * (self.width + 9) + '\r')  sys.stdout.flush()  print s  progress = self.width * self.count / self.total  sys.stdout.write('{0:3}/{1:3}: '.format(self.count, self.total))  sys.stdout.write('#' * progress + '-' * (self.width - progress) + '\r')  if progress == self.width:   sys.stdout.write('\n')  sys.stdout.flush()bar = ProgressBar(total = 10)for i in range(10): bar.move() bar.log('We have arrived at: ' + str(i + 1)) time.sleep(1)

The effect is as follows:

In this way, you can easily view the progress of the program running in some tasks, such as crawlers and machine learning, without knowing how much time it will take and so on.

The above is how to implement the progress bar function in the python console, and provides its own classes to print the progress bar, hoping to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.