Python中多进程或多线程的动态刷新打印

2024-10-05 13:36:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我实现了一个多处理下载程序。 如何打印可自动刷新的状态栏(完成率、下载速度) 在终端的不同部分。在

像这样:

    499712  [6.79%]   68k/s     // keep refreshing
    122712  [16.79%]   42k/s    // different process/thread
     99712  [56.32%]   10k/s

代码:

^{pr2}$

DownloadProcess继承Process类并触发download方法。在

我使用queue来存储url。这是开始过程

  ...
  for i in range(3):
    t = DownloadProcess(queue)
    t.start()
    for url in urls:
        queue.put(url)
  queue.join()

Tags: 代码in程序终端urlforqueueprocess
1条回答
网友
1楼 · 发布于 2024-10-05 13:36:40

下面是一个实现了多处理和多线程的演示。要尝试其中一种方法,只需取消代码顶部导入行的注释即可。如果在单行上有进度条,则可以使用打印'\r'的技术将光标移回行的开头。但如果你想有多行的进度条,那么你就得有点花哨了。每次我想打印进度条时,我都会清除屏幕。看看这篇文章console output on Unix in Python它在生成下面的代码方面帮了我很大的忙。他展示了这两种技巧。您还可以尝试一下作为python标准库一部分的curses库。问题Multiline progress bars也提出了类似的问题。主线程/进程生成执行工作的子线程,并使用队列将其进度传递回主线程。我强烈建议使用队列进行进程间/线程通信。然后,主线程显示进度并等待所有子线程结束执行,然后退出自身。在

编码

import time, random, sys, collections
from multiprocessing import Process as Task, Queue
#from threading import Thread as Task
#from Queue import Queue

def download(status, filename):
    count = random.randint(5, 30)
    for i in range(count):
        status.put([filename, (i+1.0)/count])
        time.sleep(0.1)

def print_progress(progress):
    sys.stdout.write('\033[2J\033[H') #clear screen
    for filename, percent in progress.items():
        bar = ('=' * int(percent * 20)).ljust(20)
        percent = int(percent * 100)
        sys.stdout.write("%s [%s] %s%%\n" % (filename, bar, percent))
    sys.stdout.flush()

def main():
    status = Queue()
    progress = collections.OrderedDict()
    workers = []
    for filename in ['test1.txt', 'test2.txt', 'test3.txt']:
        child = Task(target=download, args=(status, filename))
        child.start()
        workers.append(child)
        progress[filename] = 0.0
    while any(i.is_alive() for i in workers):
        time.sleep(0.1)
        while not status.empty():
            filename, percent = status.get()
            progress[filename] = percent
            print_progress(progress)
    print 'all downloads complete'

main()

演示

enter image description here

相关问题 更多 >

    热门问题