Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ember.js/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:在命令提示符下逐个打印字母_Python_String_Python 3.x_Printing_Cmd - Fatal编程技术网

Python:在命令提示符下逐个打印字母

Python:在命令提示符下逐个打印字母,python,string,python-3.x,printing,cmd,Python,String,Python 3.x,Printing,Cmd,最近我学习了Python3.4编程,阅读了关于如何编程的另一个问题,并在代码中使用了类似的def import time def type(str): for letter in str: print(letter, end='') time.sleep(0.02) print("\n") type("This sentence is typed.") 它在空闲状态下工作正常,但一旦我尝试使用Windows命令提示符运行它,CMD就会等待空

最近我学习了Python3.4编程,阅读了关于如何编程的另一个问题,并在代码中使用了类似的def

import time

def type(str):
     for letter in str:
        print(letter, end='')
        time.sleep(0.02)
    print("\n")

type("This sentence is typed.")
它在空闲状态下工作正常,但一旦我尝试使用Windows命令提示符运行它,CMD就会等待空闲时间来键入它(在本例中为半秒),然后像打印一样吐出它

我想时间睡眠声明是以这样或那样的方式被打破的,尽管

print("One")
time.sleep(2)
print("Two")
工作很好

有没有办法在短时间间隔内一次打印一封信,或者根本不可能


提前谢谢

尝试在每个字符后强制刷新
stdout
。问题是
stdout
通常被缓冲,直到输出换行符、EOF或一定数量的字节

import time
import sys

def type(str):
    for letter in str:
        print(letter, end='')
        sys.stdout.flush()
        time.sleep(0.02)
    print("\n")

type("This sentence is typed.")
或者,在Python3中,正如@PeterWood所提到的,您可以更改打印,使其自动刷新

        print(letter, end='', flush=True)

从Python 3.3开始,您可以说
print(letter,flush=True)
。“看!”彼得伍德,谢谢你的留言。我将编辑答案。