pyautocad Documentation

repository·master·Indexed 20 days ago

https://github.com/reclosedev/pyautocad

A Python library designed to simplify ActiveX automation of AutoCAD. It provides high-level abstractions for coordinate management via APoint, object iteration and filtering, and attribute caching to improve performance. The library includes the pyautocad.api module for core automation, pyautocad.types for AutoCAD-specific data types, and pyautocad.contrib.tables for importing and exporting tabular data in CSV, XLS, XLSX, and JSON formats.

Tokens
2.4K
Snippets
10
Records
17
Agent score
70%

What's inside pyautocad

  1. Access ActiveDocument and ModelSpace

    master

    The Autocad object provides shortcuts to the current active document and its ModelSpace, which are commonly used for object manipulation:

    • acad.doc: Access the current ActiveDocument.
    • acad.model: Access the ActiveDocument.ModelSpace.
  2. Use APoint for coordinate manipulation

    master

    The APoint class simplifies working with 3D points. It allows for easy coordinate arithmetic, which is useful when moving objects or calculating offsets.

    from pyautocad import APoint
    
    dp = APoint(10, 0)
    # Adding an APoint to an existing point (e.g., an object's insertion point)
    new_point = text.InsertionPoint + dp
  3. Improve performance when working with AutoCAD

    master

    ActiveX calls to AutoCAD can be slow because every attribute access (like .Text or .Position) triggers a cross-process call. Use these two methods to improve speed:

    1. Attribute Caching: Use the pyautocad.cache.Cached proxy to cache object attributes so they aren't re-fetched from AutoCAD repeatedly.
    2. Suppress Table Regeneration: When performing bulk updates on AutoCAD Table objects, use the suppressed_regeneration_of context manager to prevent the table from recalculating its layout after every single cell change.
    from pyautocad.utils import suppressed_regeneration_of
    
    # Efficiently update a table
    table = acad.model.AddTable(pos, rows, columns, row_height, col_width)
    with suppressed_regeneration_of(table):
        for row in range(rows):
            for col in range(columns):
                table.SetText(row, col, f'Cell {row},{col}')
  4. Quickstart with pyautocad

    master

    To automate AutoCAD, instantiate the Autocad class to connect to the running application. You can use APoint to handle 3D coordinates easily. The Autocad object provides access to the doc (document) and model (model space) for creating entities like Text, Lines, and Circles.

    from pyautocad import Autocad, APoint
    
    acad = Autocad()
    acad.prompt("Hello, Autocad from Python\n")
    print acad.doc.Name
    
    p1 = APoint(0, 0)
    p2 = APoint(50, 25)
    for i in range(5):
        text = acad.model.AddText('Hi %s!' % i, p1, 2.5)
        acad.model.AddLine(p1, p2)
        acad.model.AddCircle(p1, 10)
        p1.y += 10
  5. Locate AutoCAD ActiveX documentation

    master

    Since pyautocad automates AutoCAD via ActiveX, you can refer to the official AutoCAD ActiveX guide and reference for available methods and properties. These files are typically located in the help directory of your AutoCAD installation or at the following path:

    C:\Program Files\Common Files\Autodesk Shared\acadauto.chm

    Key files include:

    • acad_aag.chm: ActiveX and VBA Developer's Guide
    • acadauto.chm: ActiveX and VBA Reference
  6. Install pyautocad dependencies

    master

    To use pyautocad, you must have comtypes installed. For advanced features like Excel, CSV, or JSON import/export, you should also install xlrd and tablib.

    pip install comtypes
    # Optional for Excel/CSV/JSON support:
    pip install xlrd tablib
  7. Initialize AutoCAD connection with Autocad

    master

    Use the Autocad class to either create a new AutoCAD application instance or connect to an already running one. This is the main entry point for automation.

    from pyautocad import Autocad
    
    # Create or connect to AutoCAD
    acad = Autocad()
  8. Requirements for pyautocad

    master

    To use pyautocad, ensure the following dependencies are met:

    • comtypes: Required for ActiveX communication. Automatically installed via pip or easy_install. If installing manually, ensure comtypes is present.
    • xlrd (Optional): Required if you intend to work with tables.
    • tablib (Optional): Required if you intend to work with tables.
  9. Import and export data with Table

    master

    The Table class in pyautocad.contrib.tables simplifies reading and writing tabular data.

    Requirements:

    • xlrd and tablib must be installed.

    Supported Formats:

    • csv (Read/Write)
    • xls (Read/Write)
    • xlsx (Write only)
    • json (Read/Write)

    Example of saving AutoCAD text data to Excel and reading it back:

    from pyautocad import Autocad
    from pyautocad.contrib.tables import Table
    
    acad = Autocad()
    
    # 1. Collect data from AutoCAD
    data_to_save = []
    for text in acad.iter_objects('Text'):
        data_to_save.append([text.Text, text.InsertionPoint.x, text.InsertionPoint.y, text.InsertionPoint.z])
    
    # 2. Save to Excel
    table = Table(data_to_save)
    table.save('data.xls')
    
    # 3. Load data back from file
    loaded_table = Table.load('data.xls')
    print(loaded_table.data)
  10. Iterate and search for AutoCAD objects

    master

    You can iterate through all objects in the document or filter them by type using iter_objects().

    • Iterate all objects: Use acad.iter_objects().
    • Filter by type: Pass a type name (e.g., 'Line', 'Circle', 'Text'). The name can be partial and is case-insensitive (e.g., 'tex' matches AcDbText and AcDbMText).
    • Multiple types: You can pass multiple types to search for several object classes at once.
    • Find first match: Use conditions to find the first object that meets specific criteria.
    # Iterate all objects
    for obj in acad.iter_objects():
        print(obj)
    
    # Iterate objects of a specific type
    for line in acad.iter_objects('Line'):
        print(line)
    
    # Iterate multiple types
    for obj in acad.iter_objects(['Text', 'Circle']):
        print(obj)
    
    # Find first object matching a condition
    first_text = next(obj for obj in acad.iter_objects('Text') if '3' in obj.Text)