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

后端 未结 13 2249
深忆病人
深忆病人 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

    Well, you could always write a simple script that searches the file for import statements. This one finds all imported modules and files, including those imported in functions or classes:

    def find_imports(toCheck):
        """
        Given a filename, returns a list of modules imported by the program.
        Only modules that can be imported from the current directory
        will be included. This program does not run the code, so import statements
        in if/else or try/except blocks will always be included.
        """
        import imp
        importedItems = []
        with open(toCheck, 'r') as pyFile:
            for line in pyFile:
                # ignore comments
                line = line.strip().partition("#")[0].partition("as")[0].split(' ')
                if line[0] == "import":
                    for imported in line[1:]:
                        # remove commas (this doesn't check for commas if
                        # they're supposed to be there!
                        imported = imported.strip(", ")
                        try:
                            # check to see if the module can be imported
                            # (doesn't actually import - just finds it if it exists)
                            imp.find_module(imported)
                            # add to the list of items we imported
                            importedItems.append(imported)
                        except ImportError:
                            # ignore items that can't be imported
                            # (unless that isn't what you want?)
                            pass
    
        return importedItems
    
    toCheck = raw_input("Which file should be checked: ")
    print find_imports(toCheck)
    

    This doesn't do anything for from module import something style imports, though that could easily be added, depending on how you want to deal with those. It also doesn't do any syntax checking, so if you have some funny business like import sys gtk, os it will think you've imported all three modules even though the line is an error. It also doesn't deal with try/except type statements with regards to import - if it could be imported, this function will list it. It also doesn't deal well with multiple imports per line if you use the as keyword. The real issue here is that I'd have to write a full parser to really do this correctly. The given code works in many cases, as long as you understand there are definite corner cases.

    One issue is that relative imports will fail if this script isn't in the same directory as the given file. You may want to add the directory of the given script to sys.path.

提交回复
热议问题