17

我有一个我正在运行的算法需要一段时间,所以我想通过打印到控制台来跟踪它的进度。

所以像:

import sys

def myMethod():
    i = 0
    while (i<1000000):
        i = i+1
        output_str = str(i) + "\n"
        sys.stdout.write(output_str)  # same as print
        sys.stdout.flush()
    
myMethod()

如何在运行时而不是在结束时打印此打印件?

编辑,解决方案: - 发布修改后的代码。当您在 linux 终端中运行此代码时,它可以正常工作

 python filename.py

但是当我在 Wing 101 IDE 中运行它时——通过按下绿色播放按钮('在 python shell 中运行编辑器的内容')——它会等到程序完成后再输出。

显然不可能在 Wing IDE 中刷新标准输出。

4

2 回答 2

12
import sys

def myMethod():
    i = 0
    while (i<1000000):
        i = i+1
        output_str = str(i) + "\n"
        sys.stdout.write(output_str)  # same as print
        sys.stdout.flush()
于 2012-09-30T04:40:13.230 回答
5

这就是线程的用途。您可以同时运行一个工作线程和一个进度线程:

import time
from threading import Thread

class WorkerThread(Thread):
    def __init__(self, value=0):
        super(WorkerThread, self).__init__()

        self.value = value

    def run(self):
        while self.value < 1000:
            self.value += 1
            time.sleep(0.01)

class ProgressThread(Thread):
    def __init__(self, worker):
        super(ProgressThread, self).__init__()

        self.worker = worker

    def run(self):
        while True:
            if not self.worker.is_alive():
                print 'Worker is done'
                return True

            print 'Worker is at', self.worker.value
            time.sleep(1.0)

if __name__ == '__main__':
    worker = WorkerThread()
    progress = ProgressThread(worker)

    worker.start()
    progress.start()

    progress.join()

该命令的输出是:

Worker is at 1
Worker is at 99
Worker is at 197
Worker is at 295
Worker is at 394
Worker is at 492
Worker is at 590
Worker is at 689
Worker is at 787
Worker is at 885
Worker is at 983
Worker is done

请注意,工作线程的计数1非常快,但进度线程只是每秒报告一次进度。

于 2012-09-30T04:40:59.820 回答