2015-09-19 42 views
1

我必須分析一些python文件。爲此,我應該分析在給定文件中導入的所有模塊(即獲取此模塊的源代碼,如果它們是用Python編寫的話)。獲取導入模塊代碼的路徑

我怎樣才能獲得路徑與導入的Python模塊的文件?

我嘗試使用sys.path,但它給了所有的路徑,在哪裏呢python解釋可能搜索模塊

+0

閱讀關於「sys.modules」和「inspect.getsource」 – vaultah

回答

1

好問題被發現。我嘗試了一些東西,問題在於很多標準模塊看起來很難訪問,就像math模塊甚至不是Python,而是一個C庫(.so文件)。如果你只需要訪問用戶自定義模塊,而不是標準的,這樣的事情可以讓你的文件和資料來源:

import inspect 
import sys 

def main(): 
    # sys.modules contains a mapping between module names and module 
    # objects, but many more than the one imported in a file. dir() 
    # returns a list of names available to the local scope (also variables 
    # functions etc.). Combine those two and you get the modules available 
    # to the local scope 
    modules = [sys.modules[i] for i in dir() if i in sys.modules] 
    files = [] 
    code = [] 
    for module in modules: 
     try: 
      # modules may have a __file__ attribute 
      files.append(module.__file__) 
      # get's you the actual code 
      code.append(inspect.getsource(module)) 
     except: 
      pass 
    print(files, code) 

if __name__ == '__main__': 
    main() 

__file__是不是所有標準的模塊定義和inspect.getsource()不爲他們工作之一,這就是爲什麼try-except塊,但對於非標準模塊,這可以讓你開始。

2

對於第三方模塊,下面要打印的文件路徑。

module_file = <module_name>.__file__ 

然後您可以打印文件內容。

-1

模塊在/usr/lib/python3/dist-packages發現,在類Unix系統 和C:\Python34\Lib在Windows

+0

並非總是如此, – MattDMo