1

我正在尝试模仿matlab加载和保存功能。我正在关注这个线程:搁置代码给出了 KeyError

它很聪明。但是,如果我在单独的模块中编写该代码,并尝试导入该模块并调用该函数,则它无法访问全局变量。

具体来说,我写了一个happy.py并在里面有函数:

def save(filename='tmp', globals_=None):
    if globals_ is None:
        globals_ = globals()
        
    globals()
    import shelve
    my_shelf = shelve.open(filename, 'n')
    for key, value in globals_.items():
        if not key.startswith('__'):
            try:
                my_shelf[key] = value
            except Exception:
                print('ERROR shelving: "%s"' % key)
            else:
                print('shelved: "%s"' % key)
    my_shelf.close()

def load(filename='tmp', globals_=None):
    import shelve
    my_shelf = shelve.open(filename)
    for key in my_shelf:
        globals()[key] = my_shelf[key]
    my_shelf.close()

当我尝试

a = 1
b = 2
happy.save()

它不会给出保存ab

这是因为global()不会给模块外的对象吗?那我该怎么做我想做的事呢?

4

3 回答 3

1

以下将作为一个单独的模块工作:

import shelve
import sys
import types

EXCLUDED_TYPES = (types.ModuleType,)  # Everything can't be shelved.

def save(filename='tmp', globals_=None):
    if globals_ is None:
        globals_ = sys._getframe(1).f_globals  # Caller's globals.

    with shelve.open(filename, 'n') as my_shelf:
        for key, value in globals_.items():
            if not (key.startswith('__') or isinstance(value, EXCLUDED_TYPES)):
                try:
                    my_shelf[key] = value
                except Exception as e:
                    print('ERROR shelving: "%s"' % key, 'Exception:', e)
                else:
                    print('shelved: "%s"' % key)

def load(filename='tmp', globals_=None):
    if globals_ is None:
        globals_ = sys._getframe(1).f_globals  # Caller's globals.

    with shelve.open(filename) as my_shelf:
        for key in my_shelf:
            globals_[key]=my_shelf[key]
            print('unshelved: "%s"' % key)

一般来说,我认为函数创建这样的全局变量不是一个好主意。另请注意,这load()可能会默默地更改调用者命名空间中的现有值。

您无法轻松保存所有全局命名空间,因为除了__main__'s. 如果您真的想这样做,可以通过遍历sys.modules.

于 2013-04-01T18:37:50.780 回答
0

您可以使用inspect来查看堆栈。我定义的这个愚蠢的(命名不佳的函数)似乎可以很好地从调用命名空间中获取全局变量,尽管我没有对其进行广泛测试。我也不确定它是否适用于不同的 python 实现。(我提到这一点是因为该inspect.currentframe功能肯定是依赖于实现的)。对于它的价值,它似乎可以与 Cpython 一起工作。

import inspect
def save(globals=None):
    if globals is None:
        frames = inspect.stack()
        caller_frame = frames[-1][0]
        globals = dict((k,v) for (k,v) in caller_frame.f_globals.items() if not k.startswith('__'))
    return globals


if __name__ == "__main__":
    a = 1
    b = 2
    print save()
于 2013-04-01T17:39:10.247 回答
0

将此代码粘贴到控制台时,我没有遇到问题:

>>> def save(filename='tmp',globals_=None):
...     import shelve
...     globals_ = globals_ or globals()
...     my_shelf=  shelve.open(filename, 'n')
...     for key, value in globals_.items():
...         if not key.startswith('__'):
...             try:
...                 my_shelf[key] = value
...             except Exception:
...                 print('ERROR shelving: "%s"' % key)
...             else:
...                 print('shelved: "%s"' % key)
...     my_shelf.close()
... 
>>> def load(filename='tmp',globals_=None):
...     import shelve
...     my_shelf = shelve.open(filename)
...     for key in my_shelf:
...         globals()[key]=my_shelf[key]
...     my_shelf.close()
... 
>>> a, b = 1, 2
>>> save()
shelved: "load"
shelved: "a"
shelved: "b"
shelved: "save"

进而:

>>> def save(filename='tmp',globals_=None):
...     import shelve
...     globals_ = globals_ or globals()
...     my_shelf=  shelve.open(filename, 'n')
...     for key, value in globals_.items():
...         if not key.startswith('__'):
...             try:
...                 my_shelf[key] = value
...             except Exception:
...                 print('ERROR shelving: "%s"' % key)
...             else:
...                 print('shelved: "%s"' % key)
...     my_shelf.close()
... 
>>> def load(filename='tmp',globals_=None):
...     import shelve
...     my_shelf = shelve.open(filename)
...     for key in my_shelf:
...         globals()[key]=my_shelf[key]
...     my_shelf.close()
... 
>>> load()
>>> a, b
(1, 2)

但是当你将它作为一个模块使用时,它有点奇怪:

>>> from happy import *
>>> a, b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> load()
>>> a, b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> happy.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'happy' is not defined
>>> from happy import *
>>> a, b
(1, 2)

这里有足够的空间让你有一个解决办法吗?

于 2013-04-01T17:47:12.360 回答