Skip to content

Instantly share code, notes, and snippets.

@huntfx
Created February 2, 2021 21:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huntfx/65641778c4d14e513a92696017f1823f to your computer and use it in GitHub Desktop.
Save huntfx/65641778c4d14e513a92696017f1823f to your computer and use it in GitHub Desktop.
"""Get import dependencies using PyInstaller.
The node types can be used to check for instances.
A brief description of the main ones are below:
MissingModule: An imported module that cannot be found.
Attributes:
identifier (str)
Example:
MissingModule('invalid.module',)
SourceModule: A file that was imported.
Attributes:
identifier (str)
filename (str): Path to script
Example:
SourceModule('collections.abc', 'C:/lib/collections/abc.py')
Package: A module that was imported.
Note that files inside the package are likely to be included as
SourceModule instances.
Attributes:
identifier (str)
filename (str): Path to __init__.py,
packagepath (list): List of top level folder paths
Example:
Package('xml', 'C:/lib/xml/__init__.py', ['C:/lib/xml'])
"""
import os
from PyInstaller.depend.analysis import initialize_modgraph
from PyInstaller.lib.modulegraph.modulegraph import SourceModule, MissingModule, Package, BuiltinModule
def get_import_dependencies(*scripts):
"""Get a list of all imports required.
Args: script filenames.
Returns: list of imports
"""
script_nodes = []
scripts = set(map(os.path.abspath, scripts))
# Process the scripts and build the map of imports
graph = initialize_modgraph()
for script in scripts:
graph.run_script(script)
for node in graph.nodes():
if node.filename in scripts:
script_nodes.append(node)
# Search the imports to find what is in use
dependency_nodes = set()
def search_dependencies(node):
for reference in graph.getReferences(node):
if reference not in dependency_nodes:
dependency_nodes.add(reference)
search_dependencies(reference)
for script_node in script_nodes:
search_dependencies(script_node)
return list(sorted(dependency_nodes))
if __name__ == '__main__':
# Show the PyInstaller imports used in this file
for node in get_import_dependencies(__file__):
if node.identifier.split('.')[0] == 'PyInstaller':
print(node)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment