Advertisement
here2share

# autoimport.py

Sep 14th, 2024
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.21 KB | None | 0 0
  1. # autoimport.py
  2.  
  3. import ast
  4. import importlib
  5. import sys
  6.  
  7. def analyze_script(script_path):
  8.     with open(script_path, 'r') as file:
  9.         tree = ast.parse(file.read(), filename=script_path)
  10.    
  11.     imports = set()
  12.    
  13.     for node in ast.walk(tree):
  14.         if isinstance(node, ast.Import):
  15.             for alias in node.names:
  16.                 imports.add(alias.name)
  17.         elif isinstance(node, ast.ImportFrom):
  18.             module_name = node.module
  19.             if module_name:
  20.                 imports.add(module_name)
  21.    
  22.     return imports
  23.  
  24. def execute_imports(imports):
  25.     for module_name in imports:
  26.         try:
  27.             importlib.import_module(module_name)
  28.             print(f"Imported: {module_name}")
  29.         except ImportError as e:
  30.             print(f"Failed to import {module_name}: {e}")
  31.  
  32. def main(script_path):
  33.     imports = analyze_script(script_path)
  34.     execute_imports(imports)
  35.        
  36. if __name__ == "__main__":
  37.     if len(sys.argv) != 2:
  38.         print("Usage: python autoimport.py <path_to_main_script>")
  39.         sys.exit(1)
  40.    
  41.     main(sys.argv[1])
  42.        
  43. '''
  44. import autoimport
  45.  
  46. def calculate_area(radius):
  47.    return math.pi * radius ** 2
  48.  
  49. print(calculate_area(5))
  50. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement