简单实现python进度条脚本

yipeiwu_com6年前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构造icmp echo请求和实现网络探测器功能代码分享

python发送icmp echo requesy请求复制代码 代码如下:import socketimport struct def checksum(source_string):&...

浅谈Python中copy()方法的使用

  copy()方法返回字典的浅拷贝。 语法 以下是copy()方法的语法: dict.copy() 参数     NA 返回值...

使用 Visual Studio Code(VSCode)搭建简单的Python+Django开发环境的方法步骤

使用 Visual Studio Code(VSCode)搭建简单的Python+Django开发环境的方法步骤

写在前面的话 作为有个 Python 菜逼,之前一直用的 Pycharm,但是在主题这一块怎么调整都感觉要么太骚,看起来不舒服,要么就是简直不能看。似乎用大 JB 公司 IDE 的人似乎...

python赋值操作方法分享

一、序列赋值: x,y,z = 1,2,3 我们可以看作:x = 1,y = 2,z = 3 二、链接赋值: x = y = 1print id(x)print id(y) 大家可以看下...

Python Numpy 数组的初始化和基本操作

Python 是一种高级的,动态的,多泛型的编程语言。Python代码很多时候看起来就像是伪代码一样,因此你可以使用很少的几行可读性很高的代码来实现一个非常强大的想法。 一.基础: Nu...