如何检索另一个模块的所有局部变量?

时间:2011-04-21 18:47:35

标签: python

我收到一个模块作为参数,我想检索它的所有局部变量(没有任何与 XXX 或函数或类相关的内容)。
怎么办?

我试过了:

def _get_settings(self, module):
        return [setting for setting in dir(module) if not inspect.ismodule(setting) and not inspect.isbuiltin(setting) and not inspect.isfunction(setting) and not setting.__NAME__.startswith('__')]

但它提出了:

Traceback (most recent call last):
  File "/home/omer/Aptana Studio 3/plugins/org.python.pydev.debug_1.6.5.2011012519/pysrc/pydevd.py", line 1133, in <module>
    debugger.run(setup['file'], None, None)
  File "/home/omer/Aptana Studio 3/plugins/org.python.pydev.debug_1.6.5.2011012519/pysrc/pydevd.py", line 918, in run
    execfile(file, globals, locals) #execute the script
  File "/root/Aptana Studio 3 Workspace/website/website/manage.py", line 11, in <module>
    import settings
  File "/root/Aptana Studio 3 Workspace/website/website/settings.py", line 7, in <module>
    settings_loader = Loader(localsettings)
  File "/root/Aptana Studio 3 Workspace/website/website/envconf/loader.py", line 6, in __init__
    self.load(environment)
  File "/root/Aptana Studio 3 Workspace/website/website/envconf/loader.py", line 9, in load
    for setting in self._get_settings(module):
  File "/root/Aptana Studio 3 Workspace/website/website/envconf/loader.py", line 16, in _get_settings
    return [setting for setting in dir(module) if not inspect.ismodule(setting) and not inspect.isbuiltin(setting) and not inspect.isfunction(setting) and not setting.__NAME__.startswith('__')]
AttributeError: 'str' object has no attribute '__NAME__'

2 个答案:

答案 0 :(得分:2)

dir()返回字符串列表。直接使用setting.startswith()

答案 1 :(得分:2)

您可以使用dir()访问所有本地变量。这将返回一个字符串列表,其中每个字符串都是该属性的名称。这将返回所有变量以及方法。如果您只是专门查看实例变量,可以通过__dict__访问这些变量,例如:

>>> class Foo(object):
...     def __init__(self, a, b, c):
>>>
>>> f = Foo(1,2,3)
>>> f.__dict__
{'a': 1, 'c': 3, 'b': 2}
>>> dir(f)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'c']