Python在Windows和Colab中打印行是不同的



我试图重现《黑客帝国》开头的信息。它在Colab中工作得很好,Windows Python在几秒钟内什么也不显示,然后立即打印整个文本。删除if delete == 1:块无效

def ghostwriter(string, delete):
import time
seq = []
for i in range(len(string)):
seq.append(string[i])
for i in seq:
print(i, sep="", end="")
time.sleep(0.2)
time.sleep(3)
if delete == 1:
for i in seq:
print("b", sep="", end="")
message = {"Wake up, Neo...":1,"The Matrix has you...":1, "Follow the white rabbit.": 1, "Knock, knock, Neo.": 0}
for string in message:
ghostwriter(string, message[string])

您必须在每个打印命令之后刷新输出缓冲区,参见flush=True

def ghostwriter(string, delete):
import time
seq = []
for i in range(len(string)):
seq.append(string[i])
for i in seq:
print(i, sep="", end="", flush=True)
time.sleep(0.2)
time.sleep(3)
if delete == 1:
for i in seq:
print("b", sep="", end="")
message = {"Wake up, Neo...":1,"The Matrix has you...":1, "Follow the white rabbit.": 1, "Knock, knock, Neo.": 0}
for string in message:
ghostwriter(string, message[string])

多亏了Marcel Preda的回答,我才能够修改代码并删除"覆盖效果"。

def ghostwriter(string, delete):
import time
seq = []
for i in range(len(string)):
seq.append(string[i])
for i in seq:
print(i, sep="", end="", flush=True)
time.sleep(0.2)
time.sleep(3)
if delete == 1:
print("r", sep="", end="")
print(" "*len(seq), sep="", end="")
print("r", sep="", end="")
message = {"Wake up, Neo...":1,"The Matrix has you...":1, "Follow the white rabbit.": 1, "Knock, knock, Neo.": 0}
for string in message:
ghostwriter(string, message[string])

最新更新