python - 全局变量在 ipython 中的模块函数中不起作用

标签 python global-variables ipython

我确信有人已经回答过这个问题,但我找不到。

我有一个脚本 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/

相关文章:

javascript - 在 Google Apps 脚本中定义可跨多个项目使用的全局变量

r - 如何将多个变量和函数从全局环境导出到 foreach 循环?

python - 如何切换到 IPython 创建的 python 子进程(在 OS X 上)?

python - 将 LetsEncrypt/Certbot 与 Django 开发服务器一起使用?

python - 如果一个值相同而另一个值较低,则从列表中删除字典

python - 迭代期间循环中断 : Python, Pandas

python - 在 IPython/Jupyter Notebooks 中显示行号

python - 属性错误: 'Flask' object has no attribute 'login_manager' -- Login_Manager

c# - 我可以在我的 C# 程序中的什么地方使用全局变量?

matplotlib - 如何在 matplotlib 或 seaborn 中使用 Hershey 字体?