search
HomeBackend DevelopmentPython Tutorialpython控制台中实现进度条功能

我们大多数人都希望写一些简单的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控制台中实现进度条功能的方法,并给出了自己实现的类用来打印进度条,希望对大家的学习有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

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.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

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: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

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 vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

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.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

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: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

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.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

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 in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

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...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

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

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

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.