程序在python中运行时如何打印到控制台? [英] How can I print to console while the program is running in python?

查看:519
本文介绍了程序在python中运行时如何打印到控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何刷新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.

是这样的:

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

但是,当我在Wing 101 IDE中运行它时-按下绿色的播放按钮( python shell')-它会等到程序完成后再输出。

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.

显然是

推荐答案

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

这篇关于程序在python中运行时如何打印到控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆