Return a list of imported Python modules used in a script?

后端 未结 13 2247
深忆病人
深忆病人 2020-11-30 00:23

I am writing a program that categorizes a list of Python files by which modules they import. As such I need to scan the collection of .py files ad return a list of which mod

13条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 01:21

    I know this is old but I was also looking for such a solution like OP did. So I wrote this code to find imported modules by scripts in a folder. It works with import abc and from abc import cde format. I hope it helps someone else.

    import re
    import os
    
    
    def get_imported_modules(folder):
        files = [f for f in os.listdir(folder) if f.endswith(".py")]
    
        imports = []
        for file in files:
            with open(os.path.join(folder, file), mode="r") as f:
                lines = f.read()
                result = re.findall(r"(?

提交回复
热议问题