简单实现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设计】。

相关文章

python3如何将docx转换成pdf文件

本文实例为大家分享了python3将docx转换成pdf文件的具体代码,供大家参考,具体内容如下 直接上代码 # -*- encoding:utf-8 -*- """ auth...

python简单区块链模拟详解

python简单区块链模拟详解

最近学习了一点python,那就试着做一做简单的编程练习。 首先是这个编程的指导图,如下: 对的,类似一个简单区块链的模拟。 代码如下: class DaDaBlockCo...

在pycharm中使用git版本管理以及同步github的方法

在pycharm中使用git版本管理以及同步github的方法

注意:首先你电脑必须安装git版本控制器(软件),在官网下载即可。 pycharm中使用git以及github很简单,首先在设置中搜索github: 点击右边的Create API T...

基于Python log 的正确打开方式

保存代码到文件:logger.py import os import logbook from logbook.more import ColorizedStderrHandler...

解决tensorflow1.x版本加载saver.restore目录报错的问题

这个错误是最新的错误哈,目前只在tensorflow上的github仓库上面有提出,所以你在百度上面找不到。 是个tensorflow的bug十天前提出的,只有github仓库上一个地方...