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

标签 python console stdout wing-ide

<分区>

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

所以像这样:

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.

最佳答案

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 - 当程序在 python 中运行时,如何打印到控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12658651/

相关文章:

python - 为什么我们需要安装python模块

python - 按钮和文字闪烁

bash - 将 stderr/stdout 消息发送到函数并捕获退出信号

console - 无法在谷歌云控制台上创建新项目 - "You must select a parent organization or folder"

javascript - JS 只在 console.log 之后工作

bash - 仅当重定向到管道或文件时 awk 才没有输出

stdout - 期望只输出命令的标准输出,没有别的

python - 有没有关于覆盖 django ModelAdmin 的更好的文档

python - 如何使用 3 个列表在 Python 中创建嵌套字典

windows - 能否完全捕获 Windows 控制台应用程序的控制台输出(包括高级操作)?