How can I print to console while the program is ru

2020-02-28 05:50发布

Possible Duplicate:
How to flush output of Python print?

I have have an algorithm that I'm running that takes a while, so I want to keep track of how far it's through, by printing to the console.

So something like:

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()

How can I have this print while it's running, rather than at the end?

Edit, Solution: - Posted amended code. This code works fine when you run it in the linux terminal using

 python filename.py

But when I run it in Wing 101 IDE - by pressing the green play button ('Run the contents of the editor within the python shell') - it waits to till the program is finished before outputting.

Apparently it's not possible to flush stdout in the Wing IDE.

3条回答
仙女界的扛把子
2楼-- · 2020-02-28 06:10

This is what threads are for. You can have a worker thread and a progress thread running at the same time:

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()

The output of the command is:

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

Notice that the worker thread is counting by 1 very quickly, but the progress thread is just reporting the progress every second.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-02-28 06:11
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()
查看更多
beautiful°
4楼-- · 2020-02-28 06:20

This has already been discussed on SO.

Please check:

How to flush output of Python print?

查看更多
登录 后发表回答