小编Pur*_*uck的帖子

Ipython使用%store magic来检索动态名称

我正在尝试编写一个函数,使用magic命令检索指定名称下的文件%store. .例如,如果我已经存储了一个文件,"df"但后来想要在名称"frame"下检索它,那么我想用函数调用该函数retrieve('df','frame') 之后,变量帧将包含先前存储为df的数据帧.

但是,我不知道如何做到这一点,下面的函数只返回

"没有存储变量outputfile"

import IPython
import gc
import os
import numpy as np
import pandas as pd

path = IPython.paths.get_ipython_dir()+'\profile_default\db\\autorestore\\'
Run Code Online (Sandbox Code Playgroud)

函数检索指定名称下的存储文件(inputfile)(outputfile)

def retrieve(inputfile,outputfile='temp'):
    os.rename(r''+path+inputfile,r''+path+outputfile)
    %store -r outputfile
    os.rename(r''+path+outputfile,r''+path+inputfile)
    return


In [48]: retrieve('df','frame')
returns "no stored variable outputfile"
Run Code Online (Sandbox Code Playgroud)

关于这个/背景的原因的更多细节

主要原因是释放内存.我有一些文件,我检索使用%store,然后做一些操作或合并到另一个dataframe.在此之后我想释放使用的内存,但%xdel在使用检索的文件上运行%store -r并不释放内存.

因此我写了下面的函数,它在变量名temp下检索存储的文件.然后,我可以通过检索空文件作为临时释放内存.

#function to retrieved a stored file (inputfile) unde the variable name temp
def retrieve_temp(inputfile):
    os.rename(r''+path+inputfile,r''+path+'temp')
    %store -r temp
    os.rename(r''+path+'temp',r''+path+inputfile)
    return
Run Code Online (Sandbox Code Playgroud)

例如,在检索任何当前ram使用之前

In [5]: ram_usage()
Out[5]: …
Run Code Online (Sandbox Code Playgroud)

python memory-leaks ipython jupyter-notebook

5
推荐指数
1
解决办法
328
查看次数

标签 统计

ipython ×1

jupyter-notebook ×1

memory-leaks ×1

python ×1