为何Spyder3中“Run file”运行脚本无输出,“Run current cell”却正常?
Spyder3中Run file无输出但Run current cell正常的问题
问题现象
在Spyder3中运行以下Python脚本时,点击「Run file」按钮仅显示运行路径信息,无计算结果输出;但点击「Run current cell」按钮可正常执行并得到正确结果。
脚本代码
product = 1 for count in range(4): product = product * (count + 1) product
两种运行方式的输出
Run file输出
runfile('F:/Toshiba (j)/New Volume D/Python/factorial2.py', wdir='F:/Toshiba (j)/New Volume D/Python')
Run current cell输出
product = 1 for count in range(4): product = product * (count + 1) product Out[4]: 24
原因分析
- 「Run file」模式下,脚本作为独立Python程序执行,单独写变量名
product不会触发自动输出,Python只会计算变量值但不会主动打印。 - 「Run current cell」模式基于IPython交互式环境运行,该环境会自动显示最后一个表达式的计算结果。
解决办法
- 方法一:修改脚本,在末尾添加打印语句强制输出结果
product = 1 for count in range(4): product = product * (count + 1) print(product) # 添加这一行 - 方法二:修改Spyder运行设置,让Run file也在交互式环境执行
依次点击「Tools > Preferences > Run」,将「Console」选项设置为「Execute in current IPython console」,保存设置后再运行文件,就会自动显示最后变量的结果。
内容的提问来源于stack exchange,提问作者user28494548
相关产品推荐
相关产品推荐

