Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

在 Python 控制台裡自己做一個進度條

寫一些耗時的腳本時,能在執行過程中看到進度條,是很實用的功能——爬蟲、機器學習訓練、批次處理都適用。網上當然有 progressBar 這類現成庫,但當你需要客製化時,自己寫其實不難。

核心原理:不要換行

進度條的關鍵是「所有字元都在同一行,而且可以被覆寫」。問題是 print 會在結尾自動加上 \n,一旦換行就再也改不動了。所以我們不能再用 print。

改用 sys.stdout.write():它輸出字串但不附加任何結尾,代表這次輸出「還沒結束」。接著用 sys.stdout.flush() 把內容推到終端上(形成 print 的假象),最後寫入 \r 讓游標回到行首。下次寫入時,新內容就會覆蓋舊內容。

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)

問題二:同時要輸出其他訊息

有時候希望在進度條變化的同時,上面還要滾動一些日誌。做法是:先清掉舊行、print 出要留下的訊息,再把進度條「假輸出」一次。

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 -*-
# 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 2 語法,移植到 Python 3 時把 print s 改為 print(s)、除法加上 // 即可。)

延伸閱讀:Linux 下 Python 的安裝以及注意事項、Ubuntu 14.04 下安裝使用 Python rq 模組、無需操作系統直接運行 Python 代碼、CentOS 上源碼安裝 Python 3.4、Python 腳本獲取 Linux 系統資訊。

Copyright © Linux教程網 All Rights Reserved