Spyder 4 python程序脚本不能调用console缓存变量,对应变量未定义

解决方案

导入并运行spyder升级至版本4.0前创建的python文件(例如,在spyder 3中创建的脚本文件),console会显示

# test.py
print('result=',a)
>>>a=1
>>>runfile('E:/test.py', wdir='E:/')
>>>result=1

查看runfile的help文档,以便后面与spyder4 console里的runfile比较

help(runfile)
Help on function runfile in module spydercustomize:
runfile(filename, args=None, wdir=None, namespace=None, post_mortem=False)
    Run filename
    args: command line arguments (string)
    wdir: working directory
    post_mortem: boolean, whether to enter post-mortem mode on error

在spyder4中,运行同样的程序

# test.py
print('result=',a)
>>>a=1
>>>runfile('E:/test.py', wdir='E:/')
>>>Traceback (most recent call last):

  File "/test.py", line 1, in <module>
    print('result=',a)

NameError: name 'a' is not defined

再次查看runfile的help文档,发现 与之前的runfile相比,多了一个变量current_namespace,默认是False,如果要用console里预先缓存的变量则需要显示指定其为True。

help(runfile)
Help on function runfile in module spydercustomize:

runfile(filename=None, args=None, wdir=None, namespace=None, post_mortem=False, current_namespace=False)
    Run filename
    args: command line arguments (string)
    wdir: working directory
    namespace: namespace for execution
    post_mortem: boolean, whether to enter post-mortem mode on error
    current_namespace: if true, run the file in the current namespace

当我们指定current_namespaces=True

>>>a=1
>>>runfile('E:/test.py', wdir='E:/',current_namespace=True)
>>>result=1

问题解决~
注: 在spyder4下创建并运行的python脚本不会出现这个问题,console里会自动对current_namespace进行设定,runfile(…,current_namespace=True)

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值