我们大多数人都希望写一些简单的python脚本的同时都想能够在程序运行的过程中实现进度条的功能以便查看程序运行的速度或者进度。今天就和大家探讨这个问题:如何在python控制台中实现进度条功
进度条最主要的问题就是所有字符全部在同一行,而且可以修改。
然而当执行print语句的时候,python会在打印完这个语句的同时在结尾加上'\n',也就是换行,这就导致在控制台下一旦被print之后就无法再修改了。所以我们现在的输出就不能再使用print来完成了。
我们要使用的是来自sys库的sys.stdout.write()函数,这个函数会在控制台输出这个字符串的同时不加上任何结尾,这就意味着这个输出还没有完全结束。通过sys.stdout.flush()函数可以把输出暂时打印在控制台中(造成print的假象,我们姑且先叫这个假输出)。那么如果我们使用'\r'这个转义字符(回到行首),一切看起来是不是就合理很多了呢?
也就是说:打印字符串的时候,没有加上'\n',同时让光标回到行首,再把当前缓冲区显示出来,也就好象是print了一样,但是这时候光标还在原来的位置。
举个例子:
import sys, time for i in range(5): sys.stdout.write('{0}/5\r'.format(i + 1)) sys.stdout.flush() time.sleep(1)
在终端下执行这段代码就会得到简单的进度条效果。
接下来还需要解决两个问题:
一:清空缓冲区
有些聪明的读者可能发现,当新的字符串比之前短的时候会出现问题,比如下面这段代码:
import sys, time for i in range(5): sys.stdout.write(str(i) * (5 - i) + '\r') sys.stdout.flush() time.sleep(1)
运行后发现结果跟我们希望的不太一样。
其实是因为已经被flush出去的字符并不会主动清空,所以只有新写入的被修改了。针对这点我目前的解决方案是先输出一波空格把之前的字符串冲掉然后重新写:
import sys, time for 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)
二:固定底边输出
有时候我们希望在进度条加载的同时还有一些其他的输出。
我们不妨在刷新掉上一次输出之后输出所需输出的字符串,然后在假输出进度条。
采用如下代码:
import sys, time for 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)
就可以完成所需任务了。
怎么样,其实原理还是挺简单的吧?
这里给出一个自己实现的类用来打印进度条:
# -*- coding:utf-8 -*- # Copyright: Lustralisk # Author: Cedric Liu # Date: 2015-11-08 import sys, time class 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)
效果如下:
这样就可以方便的在一些任务中查看程序运行的进度了,比如爬虫、机器学习等并不知道要花多少时间等工作也都可以有形象的时间把握了。
以上就是在python控制台中实现进度条功能的方法,并给出了自己实现的类用来打印进度条,希望对大家的学习有所帮助。

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.