最近需要用Python寫一個小腳本,用到了一些小知識,趕緊抽空記錄一下。不深但是常用。
兩個進度條示例,拷貝就能運行:
# coding=utf-8import sysimport 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 -= 1demo1()demo2()提供一個自己寫的一個簡單異步進度條,可以在耗時操作前開啟,然后再耗時操作結束后停止。
import timeimport threadimport sysclass 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()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林站長站。
新聞熱點
疑難解答