程序在python中运行时如何打印到控制台?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12658651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I print to console while the program is running in python?
提问by dwjohnston
Possible Duplicate:
How to flush output of Python print?
可能的重复:
如何刷新 Python 打印的输出?
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
编辑,解决方案:- 发布修改后的代码。当您在 linux 终端使用
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.
但是当我在 Wing 101 IDE 中运行它时 - 通过按下绿色播放按钮('在 python shell 中运行编辑器的内容') - 它会等到程序完成后再输出。
Apparently it's not possible to flush stdout in the Wing IDE.
采纳答案by monkut
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()
回答by Blender
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 1very quickly, but the progress thread is just reporting the progress every second.
请注意,工作线程计数1非常快,但进度线程只是每秒报告进度。
回答by sureshvv
This has already been discussed on SO.
这已经在 SO 上讨论过了。
Please check:
请检查:

