print(foo, end="") 在终端中不起作用 [英] print(foo, end="") not working in terminal

查看:53
本文介绍了print(foo, end="") 在终端中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是一些应该打印文本的代码,类似于 Pokemon 的工作方式.纯粹是为了好玩.

So this is some code that is supposed to print text, similar to how Pokemon does. Purely for fun.

问题是 print(x, end="") 在终端运行程序时不起作用,但在使用 IDLE 运行时可以正常工作.

The problem is that print(x, end="") does not work when the program is run in the terminal, but it works fine when run using IDLE.

import time

lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."

for x in lorem:
    print(x, end="")
    time.sleep(0.03)

出于某种原因,如果我在 print(x, end="") 之前放置一个打印语句,程序运行良好.

For some reason the program works fine if I put a print statement before print(x, end="").

for x in lorem:
    print()
    print(x, end="")
    time.sleep(0.03)

有谁知道这是什么原因造成的?也许如何解决它?

Does anyone have any idea what is causing this? And maybe how to fix it?

推荐答案

发生这种情况是因为 python 使用缓冲区写入标准输出.为了获得预期的效果,您必须将 sys.stdout.flush() 放在代码的末尾...

This is happening because python uses a buffer to write to stdout. in order to get the desired effect, you must put sys.stdout.flush() at the end of your code...

import time, sys

lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."

for x in lorem:
    print(x, end="")
    time.sleep(0.03)
    sys.stdout.flush()

这将以每 0.03 秒 1 个字符的速率单独打印每个字符

This will print out each character individually at the rate of 1 character per 0.03 seconds

这篇关于print(foo, end="") 在终端中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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