防止ipython将输出存储在Out变量中

发布于 2021-01-29 16:39:52

我目前正在使用熊猫和ipython。由于在执行pandas数据帧时会对其进行复制,因此每个单元的内存使用量增加了500
mb。我相信这是因为数据存储在Out变量中,因为默认的python解释器不会发生这种情况。

如何禁用Out变量?

关注者
0
被浏览
50
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您的第一个选择是避免产生输出。如果您真的不需要 查看 中间结果,则可以避免它们,并将所有计算结果放在一个单元格中。

    如果需要实际显示该数据,可以使用InteractiveShell.cache_size选项设置缓存的最大大小。将此值设置为0禁用缓存。

    为此,您必须在目录下创建一个名为ipython_config.py(或ipython_notebook_config.py)的~/.ipython/profile_default文件,其内容如下:

    c = get_config()
    
    c.InteractiveShell.cache_size = 0
    

    之后,您将看到:

    In [1]: 1
    Out[1]: 1
    
    In [2]: Out[1]
    ---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    <ipython-input-2-d74cffe9cfe3> in <module>()
    ----> 1 Out[1]
    
    KeyError: 1
    

    您还可以使用命令为ipython创建不同的配置文件ipython profile create <name>。这将在~/.ipython/profile_<name>默认配置文件下创建一个新的配置文件。然后,您可以使用--profile <name>加载该配置文件的选项启动ipython 。

    另外,您可以使用%reset out魔术来重置输出缓存或使用%xdel魔术来删除特定对象:

    In [1]: 1
    Out[1]: 1
    
    In [2]: 2
    Out[2]: 2
    
    In [3]: %reset out
    
    Once deleted, variables cannot be recovered. Proceed (y/[n])? y
    Flushing output cache (2 entries)
    
    In [4]: Out[1]
    ---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    <ipython-input-4-d74cffe9cfe3> in <module>()
    ----> 1 Out[1]
    
    KeyError: 1
    
    In [5]: 1
    Out[5]: 1
    
    In [6]: 2
    Out[6]: 2
    
    In [7]: v = Out[5]
    
    In [8]: %xdel v    # requires a variable name, so you cannot write %xdel Out[5]
    
    In [9]: Out[5]     # xdel removes the value of v from Out and other caches
    ---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    <ipython-input-9-573c4eba9654> in <module>()
    ----> 1 Out[5]
    
    KeyError: 5
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看