简单实现python进度条脚本

yipeiwu_com5年前Python基础

最近需要用Python写一个小脚本,用到了一些小知识,赶紧抽空记录一下。不深但是常用。

两个进度条示例,拷贝就能运行:

# coding=utf-8

import sys
import time

# width:宽度,  percent:百分比
def progress(width, percent):
  print "\r%s %d%%" % (('%%-%ds' % width) % (width * percent / 100 * '='), percent),
  if percent >= 100:
    print
    sys.stdout.flush()


# 示例一、0%--100%
def demo1():
  for i in xrange(100):
    progress(50, (i + 1))
    time.sleep(0.1)


## 示例二、周期加载
def demo2():
  i = 19
  n = 200
  while n > 0:
    print "\t\t\t%s \r" % (i * "="),
    i = (i + 1) % 20
    time.sleep(0.1)
    n -= 1


demo1()
demo2()

提供一个自己写的一个简单异步进度条,可以在耗时操作前开启,然后再耗时操作结束后停止。

import time
import thread
import sys

class Progress:
  def __init__(self):
    self._flag = False
  def timer(self):
    i = 19
    while self._flag:
      print "\t\t\t%s \r" % (i * "="),
      sys.stdout.flush()
      i = (i + 1) % 20
      time.sleep(0.05)
    print "\t\t\t%s\n" % (19 * "="),
    thread.exit_thread()
  def start(self):
    self._flag = True
    thread.start_new_thread(self.timer, ())
  def stop(self):
    self._flag = False
    time.sleep(1)

用法:

progress = Progress()
progress.start()
time.sleep(5)
progress.stop()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中时间、日期、时间戳的转换的实现方法

1.简介 在编写代码时,往往涉及时间、日期、时间戳的相互转换。 2.示例 # 引入模块 import time, datetime 2.1 str类型的日期转换为时间戳 # 字...

Python函数中的函数(闭包)用法实例

本文实例讲述了Python闭包的用法。分享给大家供大家参考,具体如下: Python函数中也可以定义函数,也就是闭包。跟js中的闭包概念其实差不多,举个Python中闭包的例子。 d...

python实现聚类算法原理

python实现聚类算法原理

本文主要内容: 聚类算法的特点 聚类算法样本间的属性(包括,有序属性、无序属性)度量标准 聚类的常见算法,原型聚类(主要论述K均值聚类),层次聚类、密度聚类 K均值聚类...

Python基于滑动平均思想实现缺失数据填充的方法

在时序数据处理过程中,我们经常会遇到由于现实中的种种原因导致获取的数据缺失的情况,这里的数据缺失不单单是指为‘NaN'的数据,比如在AQI数据中,0是不可能出现的,这时候如果数据中出现了...

python单向链表的基本实现与使用方法【定义、遍历、添加、删除、查找等】

本文实例讲述了python单向链表的基本实现与使用方法。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #! python3 class Node()...