2013-04-23 94 views
1

我有一個嵌入python並將其內部對象模型公開爲python對象/類的應用程序。嵌入式python解釋器,生成自動完成的存根源代碼

對於自動完成/腳本編制的目的,我想提取一個包含doc標籤,結構,函數等的inernal對象模型的模擬,以便我可以將它用作IDE自動完成的庫源代碼。

有人知道一個庫,或有一些代碼片段,可用於轉儲這些類來源?

回答

2

使用dir()globals()函數來獲取已定義的列表。然後,過濾和瀏覽類使用inspect模塊

例toto.py:

class Example(object): 
    """class docstring""" 

    def hello(self): 
     """hello doctring""" 
     pass 

例browse.py:

import inspect 
import toto 

for name, value in inspect.getmembers(toto): 
    # First ignore python defined variables 
    if name.startswith('__'): 
     continue 

    # Now only browse classes 
    if not inspect.isclass(value): 
     continue 
    print "Found class %s with doctring \"%s\"" % (name, inspect.getdoc(value)) 

    # Only browse functions in the current class 
    for sub_name, sub_value in inspect.getmembers(value): 
     if not inspect.ismethod(sub_value): 
      continue 
     print " Found method %s with docstring \"%s\"" % \ 
      (sub_name, inspect.getdoc(sub_value)) 

蟒蛇browse.py:

Found class Example with doctring "class docstring" 
    Found method hello with docstring "hello doctring" 

此外,這並不真正回答你的問題,但如果你正在編寫一種IDE,你也可以使用ast模塊來解析python源文件並獲取關於它們的信息

+0

這就是我所需要的!謝謝! – 2013-05-02 22:03:17

0

Python數據結構是可變的(見What is a monkey patch?),所以提取一個模擬是不夠的。您可以使用the dir() built-in function來動態解釋可能的自動完成字符串。

+0

在這種情況下,模擬就足夠了。我不能問解釋器,因爲它被編譯到可執行文件中,但是我可以讓它執行一個腳本來轉儲內部類。 – 2013-04-29 11:20:34

+0

@RamonPoca,我不明白你。即使翻譯是嵌入和編譯的,它仍然是翻譯。請澄清你的問題,也許有一些代碼示例。 – utapyngo 2013-04-29 15:39:20

+0

另外假設用戶可以訪問解釋器,應用程序也可以嗎? – Felipe 2013-04-29 16:38:10