You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类打字机打印效果在CMD/py.exe失效,VS Code终端运行正常

问题根因
  • 该差异是Python标准输出的缓冲区机制导致的:
    • Windows CMD环境下,Python默认对标准输出采用全缓冲策略,只有缓冲区填满、遇到换行符\n、或者程序退出时,才会将缓冲区的内容批量输出到屏幕。你的代码中print使用了end=""没有输出换行符,所有打印内容都暂存在缓冲区中,直到程序运行结束才一次性输出,因此看不到逐字效果。
    • VS Code的集成终端为了优化开发调试体验,默认关闭了Python的输出缓冲,因此每次打印的内容会立刻显示,逐字效果可以正常生效。
修复方案

只需要在print语句中添加flush=True参数,强制每次打印后立即刷新输出缓冲区即可,修改后代码如下:

from time import *
from random import *

# 原代码导入的numbers模块未被使用,可直接删除
def slowPrint(line):
    for char in line:
        t = uniform(0.03, 0.3)
        # 新增flush=True参数强制刷新缓冲区
        print(char, end="", flush=True)
        sleep(t)

# Conversation
slowPrint("Message 1."), sleep(0.5), slowPrint(" Message 2.\n")

input("Press enter;")

如果不想修改print参数,也可以在每次打印后手动调用系统输出的刷新方法,效果完全一致:

import sys
from time import *
from random import *

def slowPrint(line):
    for char in line:
        t = uniform(0.03, 0.3)
        print(char, end="")
        # 手动刷新输出缓冲区
        sys.stdout.flush()
        sleep(t)

# Conversation
slowPrint("Message 1."), sleep(0.5), slowPrint(" Message 2.\n")

input("Press enter;")

内容的提问来源于stack exchange,提问作者pinkflameinthepan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:57:05