简体   繁体   English

Python在OSX终端中按字符打印字符

[英]Python printing character-by-character in OSX Terminal

I'm trying to have Python copy the contents of a .txt file into the bash terminal on OS X (10.10), but the line does not print until every single character of the line has been printed to the line. 我正在尝试让Python将.txt文件的内容复制到OS X(10.10)上的bash终端中,但是直到该行的每个字符都打印到该行后,该行才打印。 Is there any way to have Python print each line character-by-character, instead of line-by-line? 有什么方法可以让Python按字符而不是逐行打印每行? My code is designed to wait between characters, but each line simply takes a long time to print: 我的代码设计为在字符之间等待,但是每行仅花费很长时间打印:

while True:
    character = text_file.read(1)
    if not character: break
    else:
        sys.stdout.write(character)
        time.sleep(0.050)

When I run this code in IDLE, the characters print one at a time. 当我在IDLE中运行此代码时,字符一次打印一个。 In Terminal, lines take several seconds to print, and each line prints all at once. 在“终端”中,每行需要花费几秒钟的时间来打印,并且每行都一次打印所有内容。 Is there any way to reproduce the behavior I'm seeing in IDLE in Terminal? 有什么办法可以重现我在终端的IDLE中看到的行为?

if you want remove new line at the end of the line. 如果要在行末删除新行。

you can simply 你可以简单地

print character,

will remove the new line(\\n). 将删除新行(\\ n)。

Add sys.stdout.flush() after sys.stdout.write(character) sys.stdout.write(character)之后添加sys.stdout.flush() sys.stdout.write(character)

The reason should be that the output of stdout is buffered. 原因应该是stdout的输出已缓冲。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM