我确信有人已经回答过这个问题,但我找不到。
我有一个脚本 test.py
,其存在的唯一目的是将变量 var
放入全局命名空间:
def test():
global var
var = 'stuff'
以下是我在 ipython 中使用 %run
运行 test.py
,然后运行 test()
,然后尝试访问时发生的情况var
。
Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 10:22:32) [MSC v.1900 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: %run test.py
In [2]: test()
In [3]: var
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-84ddba356ca3> in <module>()
----> 1 var
NameError: name 'var' is not defined
In [4]:
知道发生了什么吗?或者一般如何将其带入本地命名空间?
最佳答案
%run
命令为文件中的全局变量创建一个单独的命名空间。它还会在执行后使用文件中定义的所有变量更新 IPython 交互式命名空间。因此,您可以在脚本中调用该函数,以便在文件完成执行之前创建全局变量:
def test():
global var
var = 'stuff'
test()
或使用%run -i
:
-i
run the file in IPython’s namespace instead of an empty one. This is useful if you are experimenting with code written in a text editor which depends on variables defined interactively.
关于python - 全局变量在 ipython 中的模块函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50122898/