2015年5月7日 星期四

學習 PYTHON

Q. 為執行的 shell command 顯示進度 progress bar (經過時間)
A. 使用 threading module 可監控背景正在執行的 shell command, 使用 progress.bar.Bar() 來顯示進度。

【範例】

import sys,os
from subprocess import Popen, PIPE
import time
from progress.bar import Bar
from threading import Thread

def reader(th):
    ## Read from the queue
    bar = Bar('processing', fill='#')
   
    while True:
        if th.is_alive() is False:
            break
          
        bar.next()
        time.sleep(1)
   
    bar.finish()
   

def work():
    p = Popen({My_Shell_Command}, shell=True, stdout=PIPE, stderr=PIPE)
    s,f = p.communicate()
    print '\nResult : '
    print s,f

def main():
    th = Thread(target=work)
    th.start()
    reader(th)

if __name__=='__main__':
    main()


沒有留言: