python:動態不刷螢幕輸出python/shell實現

膽小的皮皮發表於2019-02-18

前言
後臺執行程式有一種需求,比如檢視當前進度,想在終端看到某個值的變化情況:

先提供一種很土的辦法,把進度落地檔案為 例如 process,採用建立寫的方式。然後可以使用watch -n 1 cat process來檢視進度。

這裡提供兩種方式,python和shell

shell版本,如下(附帶一個進度條的例子)

#! /bin/bash

for ((i=0; $i<=100; i+=1))
do
    printf "progress: [%-100s] %d%%
" "xxxxxxxxxx xxx xxx" $i
    sleep 1
done
function sleepPrograss(){
    [ $# -eq 0 ] && echo "sleepPrograss Usage: sleepPrograss 10 "
    [ $# -eq 0 ] && return 1


    allTime=$1
    strDone=``
    stepTime=$(echo "scale=1; $allTime/100" | bc)
    for ((i=0; $i<=100; i+=1))
    do
        printf "progress: [%-100s] %d%%
" $strDone $i
        sleep $stepTime 
        strDone+=`#`
    done
    echo
}

python版本,如下(附一個多執行緒輸出進度的例子)

基礎用法示例

#! /usr/bin/env python

import os
import sys
import time
while 1:
    os.write(1, "
[%.3f]" % time.time())
    sys.stdout.flush()
    time.sleep(1)

子執行緒完成自己的任務,主執行緒跟蹤執行進度。

** 小編推薦一個學python的學習qun 740322234
無論你是大牛還是小白,是想轉行還是想入行都可以來了解一起進步一起學習!裙內有開發工具,很多幹貨和技術資料分享!

**

#! /usr/bin/env python 
# -*- coding: utf-8 -*-

```
@filename :   demo.py
@authors  :   U{peterguo<mailto: peterguo@tencent.com>}
@copyright:   tencent
@date     :   2012-11-15
@version  :   1.0.0.1
```
import os
import sys
import time
import thread

g_nTotal = 100
g_nProcessed = 0
g_fStartTime = time.time()

def simpleThdreadFun(interval):
    global g_nProcessed
    global g_nTotal
    while g_nTotal > g_nProcessed:
        time.sleep(interval)
        g_nProcessed += 1
    thread.exit_thread()

def test():
    
    global g_nTotal
    global g_nProcessed
    global g_fStartTime
    g_fStartTime = time.time()
    
    thread.start_new_thread(simpleThdreadFun, (1,))
    thread.start_new_thread(simpleThdreadFun, (2,))
    thread.start_new_thread(simpleThdreadFun, (3,))
    thread.start_new_thread(simpleThdreadFun, (4,))
    
    while True:
        time.sleep(0.5)
        fRunTime = time.time() - g_fStartTime
        nLeftNum = g_nTotal - g_nProcessed
        fLeftTime = fRunTime * nLeftNum / (g_nProcessed + 0.1)
        fPrograss = 100.0 * g_nProcessed / g_nTotal
        
        os.write(1, "
LeftTime[%.3f]	LeftNum[%d]	Progress[%.3f %% (%d/%d) ]" %
                   (fLeftTime, nLeftNum, fPrograss, g_nProcessed, g_nTotal))
        sys.stdout.flush()
        if g_nTotal <= g_nProcessed:
            break
    print "
Test Done, use %.3f seconds" % (time.time() - g_fStartTime)
      
if __name__==`__main__`:
    test()


相關文章