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

Python使用exec执行列表存储的代码无输出,print语句不打印问题求解

问题根因
  • instlist初始化位置错误
    你将instlist = []写在了接收指令的while循环内部,每一次循环都会先清空已存储的指令列表。当你输入end退出循环时,instlist最终是空列表,后续exec循环没有任何可执行的代码,自然不会有输出。
  • 冗余代码&缩进问题
    循环外单独书写的instlist是无意义的空语句,此外末尾等待输入的input()缩进存在错误,和上层逻辑不对齐。
修复后的代码
def main():
    opt = setup() # 假设setup函数本身逻辑正常
    inst = ''
    if opt == 'Y' or opt == 'y':
        instlist = [] # 把列表初始化移到循环外部
        while not inst == 'end':
            inst = input('Enter codeline to execute, when done type "end"')
            if not inst == 'end':
                instlist.append(inst)
        i = 0
        while i < len(instlist):
            exec(instlist[i])
            i = i + 1
        input()

修复后运行程序,输入print('hello world')再输入end,即可正常输出对应内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:36:01