解决方案
导入并运行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)