将文件加载到变量中 [英] Loading files into variables

查看:68
本文介绍了将文件加载到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个获取变量名的小函数,检查它是否存在,如果不存在,则将其从文件(使用pickle)加载到全局名称空间中.

I am trying to write a small function that gets a variable name, check if it exists, and if not loads it from a file (using pickle) to the global namespace.

我尝试在文件中使用它:

I tried using this in a file:

import cPickle

#
# Load if neccesary
#
def loadfile(variable, filename):
    if variable not in globals():
        cmd = "%s = cPickle.load(file('%s','r'))" % (variable, filename)
        print cmd
        exec(cmd) in globals()

但是它不起作用-变量未定义.我在做什么错了?

But it doesn't work - the variable don't get defined. What am I doing wrong?

推荐答案

使用'globals'存在的问题是,它仅适用于当前模块.更好的方法是直接在名称空间上使用内置的"setattr",而不是传递全局变量".这意味着您可以在实例以及模块上重用该功能.

Using 'globals' has the problem that it only works for the current module. Rather than passing 'globals' around, a better way is to use the 'setattr' builtin directly on a namespace. This means you can then reuse the function on instances as well as modules.

import cPickle

#
# Load if neccesary
#
def loadfile(variable, filename, namespace=None):
    if module is None:
        import __main__ as namespace
    setattr(namespace, variable, cPickle.load(file(filename,'r')))

# From the main script just do:
loadfile('myvar','myfilename')

# To set the variable in module 'mymodule':
import mymodule
...
loadfile('myvar', 'myfilename', mymodule)

请注意模块名称:主脚本始终是模块 main .如果您正在运行script.py并执行导入脚本",则将获得单独的代码副本,通常不是您想要的.

Be careful about the module name: the main script is always a module main. If you are running script.py and do 'import script' you'll get a separate copy of your code which is usually not what you want.

这篇关于将文件加载到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆