2011-04-21 53 views
0

我收到一個模塊作爲參數,我想檢索它的所有本地變量(沒有涉及到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__' 
+1

您可能是指'__name__',而不是'__NAME__'。 Python區分大小寫。 – geoffspear 2011-04-21 19:05:17

回答

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'] 
2

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

相關問題