我有一个运行的算法需要一段时间,因此我想通过打印到控制台来跟踪它的运行距离。
类似于:
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中编辑器的内容') - 等待直到程序完成才输出。
Apparently it's not possible to flush stdout in the Wing IDE.
答案 0 :(得分:6)
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()
答案 1 :(得分:1)
这就是线程的用途。您可以同时运行工作线程和进度线程:
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
,但进度线程只是每秒报告进度。
答案 2 :(得分:0)