79774660

Date: 2025-09-25 10:04:24
Score: 0.5
Natty:
Report link

Try the new python package available in pypi
https://pypi.org/project/AutoCAD/

import os
from AutoCAD import AutoCAD, CADException, is_autocad_running

def extract_drawing_info(file_path: str):
    """
    Connects to AutoCAD, opens a drawing, and extracts key information.

    Args:
        file_path (str): The absolute path to the DWG or DXF file.
    """
    if not os.path.exists(file_path):
        print(f"Error: The file '{file_path}' does not exist.")
        return

    acad = None
    try:
        # Check if AutoCAD is running, if not, it will be started by the AutoCAD() constructor
        if not is_autocad_running():
            print("AutoCAD is not running. The library will attempt to start it...")
        
        # 1. Connect to AutoCAD
        acad = AutoCAD()
        print("✅ Successfully connected to AutoCAD.")

        # 2. Open the specified DWG file
        print(f"\nOpening file: {file_path}")
        acad.open_file(file_path)
        print(f"✅ Successfully opened '{acad.doc.Name}'.")

        # --- Information Extraction ---

        # 3. Extract Layer Information
        print("\n" + "="*25)
        print("🎨 Extracting Layer Information")
        print("="*25)
        try:
            for layer in acad.doc.Layers:
                print(f"  - Layer Name: {layer.Name}, Color: {layer.Color}, Visible: {layer.LayerOn}")
        except Exception as e:
            print(f"Could not read layers: {e}")


        # 4. Extract Block Definitions
        print("\n" + "="*25)
        print("🧩 Extracting Block Definitions")
        print("="*25)
        try:
            user_blocks = acad.get_user_defined_blocks()
            if user_blocks:
                for block_name in user_blocks:
                    print(f"  - Found block definition: '{block_name}'")
            else:
                print("  - No user-defined blocks found in this drawing.")
        except CADException as e:
            print(f"Could not get block definitions: {e}")


        # 5. Extract Information about Specific Entities
        print("\n" + "="*25)
        print("✒️ Extracting Entity Information")
        print("="*25)
        
        # Find all LINE entities and print their start and end points
        print("\n--- Lines ---")
        lines = list(acad.iter_objects('AcDbLine'))
        if not lines:
            print("  - No lines found.")
        else:
            for i, line in enumerate(lines, 1):
                start = line.StartPoint
                end = line.EndPoint
                print(f"  Line {i}: Start=({start[0]:.2f}, {start[1]:.2f}), End=({end[0]:.2f}, {end[1]:.2f}), Layer: {line.Layer}")

        # Find all CIRCLE entities and print their center and radius
        print("\n--- Circles ---")
        circles = list(acad.iter_objects('AcDbCircle'))
        if not circles:
            print("  - No circles found.")
        else:
            for i, circle in enumerate(circles, 1):
                center = circle.Center
                print(f"  Circle {i}: Center=({center[0]:.2f}, {center[1]:.2f}), Radius={circle.Radius:.2f}, Layer: {circle.Layer}")
        
        # Find all TEXT and MTEXT entities and print their content
        print("\n--- Text & MText ---")
        text_items = list(acad.iter_objects('AcDbText')) + list(acad.iter_objects('AcDbMText'))
        if not text_items:
            print("  - No text or mtext found.")
        else:
            for i, text in enumerate(text_items, 1):
                ip = text.InsertionPoint
                print(f"  Text {i}: Content='{text.TextString}', Position=({ip[0]:.2f}, {ip[1]:.2f}), Layer: {text.Layer}")


        # 6. Find all instances of a specific block
        # IMPORTANT: Change this to a block name that actually exists in your drawing!
        target_block_name = "YOUR_BLOCK_NAME_HERE" 
        print(f"\n--- Finding coordinates for block: '{target_block_name}' ---")
        try:
            block_coords = acad.get_block_coordinates(target_block_name)
            if not block_coords:
                print(f"  - No instances of block '{target_block_name}' found.")
            else:
                for i, point in enumerate(block_coords, 1):
                    print(f"  Instance {i} found at: ({point.x:.2f}, {point.y:.2f})")
        except CADException as e:
            print(e)


    except CADException as e:
        print(f"A library error occurred: {e}")
    except Exception as e:
        # This catches errors if COM dispatch fails (e.g., AutoCAD not installed)
        print(f"An unexpected error occurred: {e}")
    finally:
        print("\nExtraction script finished.")
        if acad:
            # You can uncomment the line below if you want the script to automatically close the file
            # acad.close(save_changes=False) 
            pass


if __name__ == "__main__":
    # --- IMPORTANT ---
    # Change this path to your DWG or DXF file.
    # Use an absolute path (r"C:\...") to avoid issues.
    dwg_file_path = r"C:\Users\demo\Documents\MyProject\drawing1.dwg"
    
    extract_drawing_info(dwg_file_path)
Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: JOnes Peter