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

2024-04-29 04:48:05 发布

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

Possible Duplicate:
How to flush output of Python print?

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

比如说:

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

我怎么能在它运行的时候打印出来,而不是在最后?

编辑,解决方案:-发布修订代码。 当您使用

 python filename.py

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

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


Tags: ofto算法outputstdoutsysidehow
3条回答

这已经讨论过了。

请检查:

How to flush output of Python print?

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

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计数,但进度线程只是每秒报告一次进度。

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

相关问题 更多 >