Python:子进程调用上的简单进度条

时间:2016-03-30 07:02:19

标签: python progress-bar

我有一个简单的文件代码写入,(one.py)

one.py

from time import sleep
f = open("test.txt","w") #opens file with name of "test.txt"
sleep(1)
f.write("I am a test file.")
sleep (2)
f.write("Maybe someday, he will promote me to a real file.")
sleep (1)
f.write("Man, I long to be a real file")
sleep (1)
f.write("and hang out with all my new real file friends.")
f.close()

subpro.py

import subprocess

def oneCall():
    subprocess.call(['python','one.py'])



if __name__ == '__main__':
    print "Writing Data"
    oneCall()

当我运行subpro.py时,指示器会显示它挂起,有什么办法可以将它更改为进度条吗?这样用户就会知道背景中确实有进展?

2 个答案:

答案 0 :(得分:0)

已经存在的Python库与progressprogressbar完全相同。

您也可以自己实施,请参阅this SO post

基本上,我的想法是writeflush命令行,以便进度条看起来正在移动。

Processing |###########                     | 30%

答案 1 :(得分:0)

下面是我的解决方案。但不幸的是,加载只是在one.py和two.py完成后才完成。

如何制作

完成(one.py)

完成(two.py)

import subprocess
import time, sys
import threading
def oneCall():
    subprocess.call(['python','one.py'])

def twoCall():
    subprocess.call(['python','two.py'])


class progress_bar_loading(threading.Thread):

    def run(self):
            global stop
            global kill
            print 'Loading....  ',
            sys.stdout.flush()
            i = 0
            while stop != True:
                    if (i%4) == 0: 
                        sys.stdout.write('\b/')
                    elif (i%4) == 1: 
                        sys.stdout.write('\b-')
                    elif (i%4) == 2: 
                        sys.stdout.write('\b\\')
                    elif (i%4) == 3: 
                        sys.stdout.write('\b|')

                    sys.stdout.flush()
                    time.sleep(0.2)
                    i+=1

            if kill == True: 
                print '\b\b\b\b ABORT!',
            else: 
                print '\b\b\b done!',


kill = False      
stop = False
p = progress_bar_loading()
p.start()

try:
    #anything you want to run.
    oneCall()
    twoCall()
    time.sleep(1)
    stop = True
except KeyboardInterrupt or EOFError:
         kill = True
         stop = True