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

Python代码在Visual Studio Code可运行但Python Shell启动失败如何解决

故障原因
  • 缺失random模块导入:代码多处调用random.randint()方法,但开头没有声明import random,VS Code可以正常运行是因为编辑器的运行环境存在历史缓存,之前执行的其他代码已经加载过random模块,属于偶发的正常表现,代码本身存在导入缺失问题。
  • Python版本兼容问题:你设备上安装的Python 3.1不支持f-string语法,该语法是Python 3.6版本才正式加入的特性,如果快捷方式默认调用Python 3.1运行,会直接触发语法错误。同时不同Python版本的第三方库相互独立,你大概率仅给VS Code绑定的Python版本安装了Pillow库,快捷方式调用的Python版本未安装Pillow,会触发PIL模块找不到的报错。
  • 运行无感知问题:直接双击py文件运行时,程序执行完成后会自动关闭终端窗口,你无法看到报错信息,会误以为程序没有启动。
修复步骤
  • 补全导入语句:在代码开头添加import random。
  • 兼容低版本语法(如果需要保留Python3.1运行能力):将所有f-string替换为format写法,不需要插值的字符串直接保留原内容即可。
  • 安装对应版本依赖:给你用来运行脚本的Python版本安装Pillow库,若使用Python3.9运行,执行命令pip3.9 install pillow即可。
  • 增加窗口停留逻辑:在代码末尾添加input('执行完成,按任意键退出:'),避免程序运行完直接闪退,方便排查剩余问题。
修复后完整代码
import uuid
import random
from PIL import Image, ImageDraw

run_id = uuid.uuid1()

# 兼容低版本Python的写法,不需要兼容可换回f-string
print('Processing run_id: {}'.format(run_id))

image = Image.new('RGB', (2000, 2000))
width, height = image.size

rectangle_width = 100
rectangle_height = 100

number_of_squares = random.randint(90, 350)

draw_image = ImageDraw.Draw(image)
for i in range(number_of_squares):
    rectangle_x = random.randint(0, width)
    rectangle_y = random.randint(0, height)

    rectangle_shape = [
        (rectangle_x, rectangle_y),
        (rectangle_x + rectangle_width, rectangle_y + rectangle_height)]
    draw_image.rectangle(
        rectangle_shape,
        fill=(
            random.randint(0, 255),
            random.randint(0, 255),
            random.randint(0, 255)
        )
    )

image.save('output.png')
image.show('output.png')

# 防止闪退,不需要可以删除
input('执行完成,按任意键退出:')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:06:08