且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将文件加载到变量中

更新时间:2023-01-21 19:22:54

使用'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.