IPython loading variables to workspace: can you think of a better solution than this?

不打扰是莪最后的温柔 提交于 2019-12-01 09:47:01

If I save this as load_on_run.py:

import argparse
import numpy as np
if __name__=='__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-l','--list', help='list variables', action='store_true')
    parser.add_argument('filename')
    __args = parser.parse_args()
    data = np.load(__args.filename)
    locals().update(data)
    del parser, data, argparse, np
    if __args.list:
        print([k for k in locals() if not k.startswith('__')])
    del __args

And then in ipython I can invoke it with %run:

In [384]: %run load_on_run testarrays.npz -l
['array2', 'array3', 'array4', 'array1']
In [385]: array3
Out[385]: array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1])

It neatly loads the arrays from the file into the ipython workspace.

I'm taking advantage of the fact that magic %run runs a script, leaving all functions and variables defined by it in the main namespace. I haven't looked into how it does this.

The script just takes a few arguments, loads the file (so far only .npz), and uses the locals().update trick to put its variables into the local namespace. Then I clear out the unnecessary variables and modules, leaving only the newly loaded ones.

I could probably define an alias for %run load_on_run.

I can also imagine a script along these lines that lets you load variables with an import: from <script> import *.

You could assign the values in the npz file to global variables:

import numpy as np

def spill(filename):
    f = np.load(filename)
    for key, val in f.iteritems():
        globals()[key] = val
    f.close()

This solution works in Python2 and Python3, and any flavor of interative shell, not just IPython. Using spill is fine for interactive use, but not for scripts since

  1. It gives the file the ability to rebind arbitrary names to arbitrary values. That can lead to surprising, hard to debug behavior, or even be a security risk.
  2. Dynamically created variable names are hard to program with. As the Zen of Python (import this) says, "Namespaces are one honking great idea -- let's do more of those!" For a script it is better to keep the values in the NpzFile, f, and access them by indexing, such as f['x'].
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!