我必須分析一些python文件。爲此,我應該分析在給定文件中導入的所有模塊(即獲取此模塊的源代碼,如果它們是用Python編寫的話)。獲取導入模塊代碼的路徑
我怎樣才能獲得路徑與導入的Python模塊的文件?
我嘗試使用sys.path
,但它給了所有的路徑,在哪裏呢python解釋可能搜索模塊
我必須分析一些python文件。爲此,我應該分析在給定文件中導入的所有模塊(即獲取此模塊的源代碼,如果它們是用Python編寫的話)。獲取導入模塊代碼的路徑
我怎樣才能獲得路徑與導入的Python模塊的文件?
我嘗試使用sys.path
,但它給了所有的路徑,在哪裏呢python解釋可能搜索模塊
好問題被發現。我嘗試了一些東西,問題在於很多標準模塊看起來很難訪問,就像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
塊,但對於非標準模塊,這可以讓你開始。
對於第三方模塊,下面要打印的文件路徑。
module_file = <module_name>.__file__
然後您可以打印文件內容。
閱讀關於「sys.modules」和「inspect.getsource」 – vaultah