当程序在python中运行时,如何打印到控制台?

How can I print to console while the program is running in python?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
How to flush output of Python print?

我有一个算法要运行一段时间,所以我想通过打印到控制台来跟踪它运行了多远。

比如:

1
2
3
4
5
6
7
8
9
10
11
12
import sys

def myMethod():
    i = 0
    while (i<1000000):
        i = i+1
        output_str = str(i) +"
"

        sys.stdout.write(output_str)  # same as print
        sys.stdout.flush()

myMethod()

我怎么能在印刷品运行时使用它,而不是在最后?

编辑,解决方案:发布修订代码。当您在Linux终端上使用

1
 python filename.py

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

很明显,不可能在侧翼冲洗性病。


1
2
3
4
5
6
7
8
9
10
import sys

def myMethod():
    i = 0
    while (i<1000000):
        i = i+1
        output_str = str(i) +"
"

        sys.stdout.write(output_str)  # same as print
        sys.stdout.flush()


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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()

命令的输出为:

1
2
3
4
5
6
7
8
9
10
11
12
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计数,但是进度线程只是每秒报告一次进度。


这已经被讨论过了。

请检查:

如何刷新python print的输出?