Coder Social home page Coder Social logo

pyautocad's Introduction

pyautoacad - AutoCAD Automation for Python

This library aimed to simplify writing ActiveX Automation scripts for AutoCAD with Python

Requires:

Optional:

Features:

  • Simplifies work with coordinates (3D points)
  • Efficient objects iteration and searching (with casting to correct type)
  • Excel/csv/json import and export (xlrd and tablib required)

Simple usage example:

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

dp = APoint(10, 0)
for text in acad.iter_objects('Text'):
    print('text: %s at: %s' % (text.TextString, text.InsertionPoint))
    text.InsertionPoint = APoint(text.InsertionPoint) + dp

for obj in acad.iter_objects(['Circle', 'Line']):
    print(obj.ObjectName)

See more examples in source distribution.

Links

pyautocad's People

Contributors

kanzure avatar reclosedev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyautocad's Issues

PyAutoCAD & Python 2.5

I am getting an attribute error from the initial import of the module. I am using pyautocad 0.1.2, python 2.5.1 & comtypes 0.6.2 on Win7 32Bit system.

Using example

from pyautocad import Autocad, APoint

acad = Autocad()
p1 = APoint(0.0, 0.0)
acad.model.AddCircle(p1, 0.5)

Get the following error;

Traceback (most recent call last):
  File "C:\Program Files\ArcGIS\ArcToolBox\Scripts\GWtest.py", line 31, in 
    from pyautocad import Autocad, APoint
  File "C:\Python25\Lib\site-packages\pyautocad\__init__.py", line 15, in 
    from pyautocad.api import *
  File "C:\Python25\Lib\site-packages\pyautocad\api.py", line 26, in 
    import pyautocad.types
  File "C:\Python25\Lib\site-packages\pyautocad\types.py", line 17, in 
    class APoint(array.array):
  File "C:\Python25\Lib\site-packages\pyautocad\types.py", line 65, in APoint
    @x.setter
AttributeError: 'property' object has no attribute 'setter'

Any help most appreciated.

Owain

Is it possible to draw surfaces and Volumes using Pyautocad ?

Hello,

I'm trying to draw several building automatically using python, so far using APoint, line and AddCircle, i'm able to add columns and slabs. But every thing is linear. I wanted to know if there was a way to draw a surface, or Extrude would be PERFECT.

Thank you all for your help :D

cannot find cad

i installed 2 versions of autocad cad2017 and cad2014 mechanical ,
i used code like this:

from pyautocad import Autocad
a=Autocad()
a.prompt("hello")

cad2014 mechanical was opened , why not cad2017?
how to run this in cad2017?

facing COM error

Hi i tried a small code as shown below
`from pyautocad import Autocad, APoint

acad = Autocad(create_if_not_exists=True)
acad.prompt("Hello, Autocad from Python\n")
print(acad.doc.Name)

for obj in acad.iter_objects():
print(obj.ObjectName)`

I am getting an error. COMError: (-2147417851, 'The server threw an exception.', (None, None, None, 0, None))

I am using python 3.7.7 , win10 64 bit and autocad mechanical 2019 with vba enabler engine installed.

How to use the AddMLine?

I know how to use the AddLine or the AddCircle. But i don't find the answer.Could someone tell me?

pyautocad - windows 8 (64 bits) and AutoCAD 2013

I have a new computer with windows 8 (64 bits) and I installAutoCAD 2013.

I´ve tried a routine that used to work in windows 7 (32 bits) + AutoCAD 2008.....here is the error:

Exception WindowsError: 'exception: stack overflow' in <bound method tagVARIANT.del of VARIANT(vt=0x8, u'Digite ABA da cantoneira: ')> ignored
Exception WindowsError: 'exception: access violation writing 0x0000000000040000' in <bound method BSTR.del of BSTR(None)> ignored

Running functions that takes in symbol as input

I'm just wondering, how can you pass on symbols as arguments here? For example, I very much need to use the GetBoundingBox and GetEntity function, but I can't seem to get this working because both function need to take in a symbol.

image

Or if this is not possible, then what's the other alternative to solve this?

import dxf from path and paste it on my draw

Hi to everyone,
I'm trying since last week to copy from a directory X:\windows\cad\repo\file_to_import.dxf
and paste to X:\windows\cad\new_file.dxf , but i have to paste the previous (file_to_import.dxf) in a specific layer number and X Y Coordinates.
I cant find how..
In the Docs i dont see some import command or how to write directly in the autocad terminal.
If i can write in the terminal i can do the task..
I dont want someone to write my code, i want to learn the pyautocad's command for do this job.

Thanks to everyone
Arti

Cannot create Autocad object

I tried the following :
from pyautocad import Autocad, APoint
acad = Autocad(create_if_not_exists=True)
acad.prompt("Hello, Autocad from Python\n")

The following is the error i m getting :

acad.prompt("Hello, Autocad from Python\n")
Hello, Autocad from Python Traceback (most recent call last):
File "C:\Users\snehal\AppData\Local\Programs\Python\Python36\lib\site-packages\pyautocad\api.py", line 62, in app
self.app = comtypes.client.GetActiveObject('AutoCAD.Application', dynamic=True) File"C:\Users\snehal\AppData\Local\Programs\Python\Python36\lib\sitepackages\comtypes\client_init.py", line 173, in GetActiveObject
clsid = comtypes.GUID.from_progid(progid)
File "C:\Users\snehal\AppData\Local\Programs\Python\Python36\lib\site-packages\comtypes\GUID.py", line 78, in from_progid
_CLSIDFromProgID(str(progid), byref(inst))
File "_ctypes/callproc.c", line 918, in GetResult
OSError: [WinError -2147221005] Invalid class string During handling of the above exception, another exception occurred: Traceback (most recent call last):
File "", line 1, in
File "C:\Users\snehal\AppData\Local\Programs\Python\Python36\lib\site-packages\pyautocad\api.py", line 161, in prompt
self.doc.Utility.Prompt(u"%s\n" % text)
File "C:\Users\snehal\AppData\Local\Programs\Python\Python36\lib\site-packages\pyautocad\api.py", line 73, in doc
return self.app.ActiveDocument
File "C:\Users\snehal\AppData\Local\Programs\Python\Python36\lib\site-packages\pyautocad\api.py", line 66, in app
self.app = comtypes.client.CreateObject('AutoCAD.Application', dynamic=True) File "C:\Users\snehal\AppData\Local\Programs\Python\Python36\lib\sitepackages\comtypes\client_init.py", line 227, in CreateObject
clsid = comtypes.GUID.from_progid(progid)
File "C:\Users\snehal\AppData\Local\Programs\Python\Python36\lib\site-packages\comtypes\GUID.py", line 78, in from_progid
_CLSIDFromProgID(str(progid), byref(inst))
File "_ctypes/callproc.c", line 918, in GetResult
OSError: [WinError -2147221005] Invalid class string

I am using Python3.6 ,Autocad 2016,Windows 8 (64bit). Please provide me the solution. Thank you

Read Custom DWGProps

I have been tasked with writing something to read through the custom DWGProps in an AutoCAD drawing. Is this possible using pyautocad?

_ctypes.COMError, need help

Hi reclosedev,
Your lib helps a lot...
And here are 2 question I wand to ask.
The first one is can I save the drawing use acad.doc.save(r'C:\Users\Administrator\Desktop\1.dwg')
or acad.doc.save(r'C:\Users\Administrator\Desktop\1.dwg')?

the example code below:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pyautocad import Autocad, APoint

acad = Autocad(create_if_not_exists=True)
acad.prompt("Hello, Autocad from Python\n")
print acad.doc.Name
try:
    acad.doc.save(r'C:\Users\Administrator\Desktop\1.dwg')
except Exception as e:
    print e

The exception show
_ctypes.COMError (-2147352562, '\xce\xde\xd0\xa7\xb5\xc4\xb2\xce\xca\xfd\xca\xfd\xc4\xbf\xa1\xa3', (None, None, None, 0, None))

The second question is how to hatch an object.The doc of ActiveX/VBA gives a VBA code below:

Sub Ch4_AppendInnerLoopToHatch()
    Dim hatchObj As AcadHatch
    Dim patternName As String
    Dim PatternType As Long
    Dim bAssociativity As Boolean

    ' 定义和创建图案填充
    patternName = "ANSI31"
    PatternType = 0
    bAssociativity = True
    Set hatchObj = ThisDrawing.ModelSpace. _
        AddHatch(PatternType, patternName, bAssociativity)

    ' 创建图案填充的外部环
    Dim outerLoop(0 To 1) As AcadEntity
    Dim center(0 To 2) As Double
    Dim radius As Double
    Dim startAngle As Double
    Dim endAngle As Double
    center(0) = 5: center(1) = 3: center(2) = 0
    radius = 3
    startAngle = 0
    endAngle = 3.141592
    Set outerLoop(0) = ThisDrawing.ModelSpace. _
       AddArc(center, radius, startAngle, endAngle)
    Set outerLoop(1) = ThisDrawing.ModelSpace. _
       AddLine(outerLoop(0).startPoint, outerLoop(0).endPoint)

    ' 将外部环附加到 Hatch 对象
    hatchObj.AppendOuterLoop (outerLoop)

    ' 创建一个圆作为图案填充的内部环
    Dim innerLoop(0) As AcadEntity
    center(0) = 5: center(1) = 4.5: center(2) = 0
    radius = 1
    Set innerLoop(0) = ThisDrawing.ModelSpace. _
                                 AddCircle(center, radius)

    ' 将圆作为内部环附加到图案填充
    hatchObj.AppendInnerLoop (innerLoop)

    ' 计算并显示图案填充
    hatchObj.Evaluate
    ThisDrawing.Regen True
End Sub

the code hatchObj.AppendInnerLoop (innerLoop) how to rewrite use python?
Need your help, thanks a lot.

To get the coordinate of the intersection point of a grid by clicking the point

When I run this python code for the captioned, the error occured as follows, File "c:\Users\sonsun\AppData\Local\Programs\Python\Python311\Lib\site-packages\comtypes\automation.py", line 843, in _invoke
self.__com_Invoke(memid, riid_null, lcid, invkind, dp, var, None, argerr)
_ctypes.COMError: (-2147352567, '예외가 발생했습니다.', ('Invalid argument Point in GetPoint', 'AutoCAD', 'C:\Program Files\Autodesk\AutoCAD 2019\HELP\OLE_ERR.CHM', -2145320939, None))
for the following code,
from pyautocad import Autocad, APoint
acad = Autocad(create_if_not_exists=True)
doc = acad.ActiveDocument
def gpuser():
sp = APoint(0, 0, 0) # Initializing sp with coordinates (0, 0, 0)
ep = APoint(0, 0, 0) # Initializing ep with coordinates (0, 0, 0)
rp = APoint(0, 0, 0) # Initializing rp with coordinates (0, 0, 0)
sp = doc.Utility.GetPoint("\nBottom-left corner on the column:")
ep = doc.Utility.GetPoint("\nBottom-right corner on the column:")
rp = doc.Utility.GetPoint("\nTop-left corner on the row:")
print("sp(1) input =", sp[0]) # Assuming you want to print the X coordinate of the 'sp' point
gpuser()
How can I fix the error and to get the correct response from the active autocad drawing.
Thanks in advance,
Sun, Son

Read&Write DWG

There is a task to automate the routine process associated with Autocad 2020 LT. You need to insert the same table into 180 DWG files (it's not a problem to load it in Python). The method for opening the file doesn't work:

from pyautocad import Autocad, APoint
acad = Autocad()
acad.prompt("Hello, Autocad from Python\n")
print(acad.doc.Name)

Help me, please if it possible.

_ctypes.COMError

when type the example:

for obj in acad.iter_objects():
    print obj.ObjectName

a bug occurred
Traceback (most recent call last):
File "<pyshell#10>", line 1, in
for obj in acad.iter_objects():
File "C:\Program Files\Python36\lib\site-packages\pyautocad\api.py", line 128, in iter_objects
item = self.best_interface(item)
File "C:\Program Files\Python36\lib\site-packages\pyautocad\api.py", line 156, in best_interface
return comtypes.client.GetBestInterface(obj)
File "C:\Program Files\Python36\lib\site-packages\comtypes\client_init_.py", line 126, in GetBestInterface
result = punk.QueryInterface(interface)
File "C:\Program Files\Python36\lib\site-packages\comtypes\client\lazybind.py", line 142, in QueryInterface
return self.comobj.QueryInterface(*args)
File "C:\Program Files\Python36\lib\site-packages\comtypes_init
.py", line 1156, in QueryInterface
self.__com_QueryInterface(byref(iid), byref(p))
_ctypes.COMError: (-2147467262, '不支持此接口', (None, None, None, 0, None))

typ = _vartype_to_ctype[self.vt & ~VT_ARRAY]

hello,i need your help.
i read your doc and try to use other function referening AutoCAD ActiveX documentation.
but find some error,however the function did work.
here is the codes(quite simple):

#---------------------------------------------------------------------------
from pyautocad import Autocad, APoint
acad = Autocad(create_if_not_exists=True)
p1 = APoint(0, 0, 0)
p2 = APoint(25, 0, 0)
p3 = APoint(60, 60)
line = acad.model.AddLine(p1, p2)
offset = line.Offset(12)

#---------------------------------------------------------------------------
and here is the message:

D:\pythonWorkSpace\first_folder\Scripts\python.exe D:/workspace/first_python/manipulate_cad/TestCad.py
Traceback (most recent call last):
File "D:/workspace/first_python/manipulate_cad/TestCad.py", line 14, in
offset = line.Offset(12)
File "D:\pythonWorkSpace\first_folder\lib\site-packages\comtypes\client\lazybind.py", line 182, in caller
return self._comobj._invoke(descr.memid, descr.invkind, 0, *args)
File "D:\pythonWorkSpace\first_folder\lib\site-packages\comtypes\automation.py", line 730, in _invoke
return var._get_value(dynamic=True)
File "D:\pythonWorkSpace\first_folder\lib\site-packages\comtypes\automation.py", line 457, in _get_value
typ = _vartype_to_ctype[self.vt & ~VT_ARRAY]
KeyError: 9

Process finished with exit code 1

#---------------------------------------------------------------------------
the same error occured when i use '' line.ArrayPolar(3, 3.14, p1)''
But just as i said, auto cad did work well and draw the graphics rightly.
How can i settle this? I need your help.
By the way ,the version of my auto cad is 2018.
Thanks~!

why my script doesn't iterate all text objects

Hello, I have a problem, I wrote some script and I want to iterate all the text in my model space and redefine changed texts.

Some texts are not iterated, Some texts iterated two times and rest of them are ok.

you can take script also, I have something like 2000 object for the testing purpose, they are all the same I just want to use this script in the project, I have to renumber chainages and add all of them 0.51m. how can I fix this problem?
I think it is a pyautocad problem, every time when you just iterate texts by regular expression search it skips some text, but only cases when you use obj.Delete() or obj.Move() functions, if you just ask to show all object it will show you all of them, but if you try to change position or delete them it will skip some objects, I think some operations happens quicker then others.

`from pyautocad import Autocad, APoint

import re

acad = Autocad()
pattern = re.compile("([0-9]+)+([0-9]+).([0-9]+)") # Example 37+45.63

addValue = 51 # Value To add a Chainage 0.51m

for text in acad.iter_objects('Text',limit = None):

if pattern.search(text.TextString):  #Check only Texts where patter has been found
    textContent = text.TextString    # Get full Text content for reuse
    
    
    getCoord = text.InsertionPoint #Get Existing Text Coordinates
    coord = APoint(getCoord)   #Set Coordinate for new Text
    rotation = text.Rotation # Get existing Text Rotation
    height = text.Height    # Get existing Text Height
    
    
    finded = pattern.search(textContent)# Finded Pattern Text
    a = int(finded.group(1)) # Regex Group 1 example (37)+45.63
    b = int(finded.group(2)) # Regex Group 2 example  37+(45).63
    c = int(finded.group(3)) # Regex Group 3 example  37+45.(63)
    
    ###################################################
    sum1 = c + addValue   #######
    if sum1 >= 100:       #######
        c = sum1 - 100    #######
        b += 1            #######
        if b + 1 >= 100:  ####### This section must be 
            a += 1        ####### A seperate Function But 
            b -= 100      ####### I did not manage
    else:                 #######
        c = sum1          #######
    ########################################################  
      
    modStr = pattern.sub(f'{a}+{b}.{c}', textContent) # Modified Text To be Placed
    text.Delete()   #Delete text to reinsert
    
    newText = acad.model.AddText(modStr, coord, height) #Create New text objects in the model
    newText.rotation = rotation # Add same rotations as source before deleting

print("Done!")`

_ctypes.COMError: (-2147467262, 'No such interface supported', (None, None, None, 0, None))

Similar to 17
At the line:

for obj in acad.iter_objects('Text'):

I get :

File "d:\CODE\pyautocad\tutorial.py", line 15, in <module>
    for obj in acad.iter_objects('Text'):
  File "C:\Users\user\AppData\Roaming\Python\Python39\site-packages\pyautocad\api.py", line 128, in iter_objects
    item = self.best_interface(item)
  File "C:\Users\user\AppData\Roaming\Python\Python39\site-packages\pyautocad\api.py", line 156, in best_interface
    return comtypes.client.GetBestInterface(obj)
  File "C:\ProgramData\Anaconda3\lib\site-packages\comtypes\client\__init__.py", line 126, in GetBestInterface
    result = punk.QueryInterface(interface)
  File "C:\ProgramData\Anaconda3\lib\site-packages\comtypes\client\lazybind.py", line 142, in QueryInterface
    return self._comobj.QueryInterface(*args)
  File "C:\ProgramData\Anaconda3\lib\site-packages\comtypes\__init__.py", line 1152, in QueryInterface
    self.__com_QueryInterface(byref(iid), byref(p))
_ctypes.COMError: (-2147467262, 'No such interface supported', (None, None, None, 0, None))

Cann't open autocad

I run the example, but cann't do it!
Traceback (most recent call last):
File "test.py", line 5, in
acad.prompt("Hello, Autocad from Python\n")
File "C:\Program Files\Miniconda2\lib\site-packages\pyautocad\api.py", line 162, in prompt
self.doc.Utility.Prompt(u"%s\n" % text)
File "C:\Program Files\Miniconda2\lib\site-packages\pyautocad\api.py", line 74, in doc
return self.app.ActiveDocument
File "C:\Program Files\Miniconda2\lib\site-packages\pyautocad\api.py", line 63, in app
self.app = comtypes.client.GetActiveObject('AutoCAD.Application', dynamic=True)
File "C:\Program Files\Miniconda2\lib\site-packages\comtypes\client_init
.py", line 173, in GetActiveObject
clsid = comtypes.GUID.from_progid(progid)
File "C:\Program Files\Miniconda2\lib\site-packages\comtypes\GUID.py", line 78, in from_progid
_CLSIDFromProgID(unicode(progid), byref(inst))
File "_ctypes/callproc.c", line 946, in GetResult
WindowsError: [Error -2147221005]
I use win7, python 2.7 64bit. Autocad2014

need help,run the samlpe ,error:

Hello, Autocad from Python

Drawing1.dwg

COMError Traceback (most recent call last)
in ()
15
16 dp = APoint(10, 0)
---> 17 for text in acad.iter_objects('Text'):
18 print('text: %s at: %s' % (text.TextString, text.InsertionPoint))
19 text.InsertionPoint = APoint(text.InsertionPoint) + dp

D:\pythonp\anaconda2\lib\site-packages\pyautocad\api.pyc in iter_objects(self, object_name_or_list, block, limit, dont_cast)
126 continue
127 if not dont_cast:
--> 128 item = self.best_interface(item)
129 yield item
130

D:\pythonp\anaconda2\lib\site-packages\pyautocad\api.pyc in best_interface(self, obj)
154 def best_interface(self, obj):
155 """ Retrieve best interface for object """
--> 156 return comtypes.client.GetBestInterface(obj)
157
158 def prompt(self, text):

D:\pythonp\anaconda2\lib\site-packages\comtypes\client_init_.pyc in GetBestInterface(punk)
124 # Could the above code, as an optimization, check that QI works,
125 # before generating the wrapper module?
--> 126 result = punk.QueryInterface(interface)
127 logger.debug("Final result is %s", result)
128 return result

D:\pythonp\anaconda2\lib\site-packages\comtypes\client\lazybind.pyc in QueryInterface(self, *args)
140 def QueryInterface(self, *args):
141 "QueryInterface is forwarded to the real com object."
--> 142 return self._comobj.QueryInterface(*args)
143
144 def cmp(self, other):

D:\pythonp\anaconda2\lib\site-packages\comtypes_init_.pyc in QueryInterface(self, interface, iid)
1156 if iid is None:
1157 iid = interface.iid
-> 1158 self.__com_QueryInterface(byref(iid), byref(p))
1159 clsid = self.dict.get('__clsid')
1160 if clsid is not None:

COMError: (-2147467262, '\xb2\xbb\xd6\xa7\xb3\xd6\xb4\xcb\xbd\xd3\xbf\xda', (None, None, None, 0, None))

can not delete

from pyautocad import Autocad
acad = Autocad()
for obj in acad.iter_objects_fast():
obj.Delete

it doesn't work,I can add layers or other entities,but I can not delete anything

Error when trying example usage.

I'm getting this output when trying the example code.

acad.model.AddLineFailed to format the args
Traceback (most recent call last):
File "C:\Python27\Lib\site-packages\pythonwin\pywin\idle\CallTips.py", line 130, in get_arg_text
argText = inspect.formatargspec(*arg_getter(fob))
File "C:\Python27\lib\inspect.py", line 815, in getargspec
raise TypeError('{!r} is not a Python function'.format(func))
TypeError: <COM method offset 71: WinFunctionType at 0x0000000004F20E18> is not a Python function

when trying simply

from pyautocad import Autocad, Apoint
acad = Autocad()
p1 = APoint(0,0)
p2=Apoint(50,25)
acad.model.AddLine(p1,p2)

I get

Traceback (most recent call last):
File "", line 1, in
_ctypes.COMError: (-2147352568, 'Bad variable type.', (None, None, None, 0, None

delete all objects error

Hi all,

I get this error when deleting all objects, but it is ok to delete an object individually.

from pyautocad import Autocad, APoint
acad = Autocad(create_if_not_exists=True)

L1 = acad.model.AddLine(APoint(0,0), APoint(500,250))
L2 = acad.model.AddLine(APoint(0,100), APoint(500,600))

for obj in acad.iter_objects():
    obj.Delete()

it returns:

COMError                                  Traceback (most recent call last)
d:\02 Work\02 Projects Piotr\LEARNING\pyautocad_learn\math_array_autocad.py in <cell line: 1>()
----> 1 for obj in acad.iter_objects():
      2     obj.Delete()

~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pyautocad\api.py in iter_objects(self, object_name_or_list, block, limit, dont_cast)
    118         count = block.Count
    119         for i in xrange(count):
--> 120             item = block.Item(i)  # it's faster than `for item in block`
    121             if limit and i >= limit:
    122                 return

~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\comtypes\client\lazybind.py in caller(*args)
    180             # DISPATCH_METHOD
    181             def caller(*args):
--> 182                 return self._comobj._invoke(descr.memid, descr.invkind, 0, *args)
    183             try:
    184                 caller.__name__ = name

~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\comtypes\automation.py in _invoke(self, memid, invkind, lcid, *args)
    743             dp.rgvarg = array
    744 
--> 745         self.__com_Invoke(memid, riid_null, lcid, invkind,
    746                           dp, var, None, argerr)
    747         return var._get_value(dynamic=True)

COMError: (-2147352567, 'Exception occurred.', (None, None, None, 0, None))

I noticed (from AutoCAD) the first object is deleted but not the 2nd one (in the case of two objects).
If I have a lot of objects, some are deleted, and some are not.

It is ok when i do L1.Delete() or L2.Delete(),

Is there anything wrong? Thanks a lot!

system: Windows 10, Python 3.9.13, pyautocad 0.2.0 , AutoCAD 2023

-teko-

Incompatible with python 3.x

The library's source files contain syntax incompatible with python 3.x, notably the print statement (when it should be a function). The syntax is otherwise not yet adapted for python 3.x, e.g.: old-style string formatting (the % operator), old-style exception handlers (comma instead of 'as'), and so on. The total amount of corrections to be made for python 3.x support is not so large.

As of version 0.1.3, pyautocad causes syntax errors on python 3.4. Please update the library ASAP.

AddRegion - problem with array

Hi....first I'd like to thanks. This Python connection with AutoCAD is very usefull!!!

My goal is to create a solid.....but before the AddExtrudedSolid I need to create a Region (AddRegion).

The problem is to bulid the array correctly. The examle below is to draw a "L" shape....user must inform the width and tickness.

Thanks again,

Luciano

from pyautocad import *
from array import *
from math import radians

acad = Autocad()
desenho = acad.model
documento = acad.doc

aba = acad.doc.Utility.GetString(1,'Digite ABA da cantoneira: ')
espessura = acad.doc.Utility.GetString(1,'Digite ESPESSURA da cantoneira: ')

insersao = acad.doc.Utility.GetPoint(APoint(0,0,0),'Pto de insercao: ')
p1 = array('d', insersao)

p2 = acad.doc.Utility.PolarPoint(p1, radians(0), float(aba))
p3 = acad.doc.Utility.PolarPoint(array('d', p2), radians(90), float(espessura))
p4 = acad.doc.Utility.PolarPoint(array('d', p3), radians(180), float(aba)-float(espessura))
p5 = acad.doc.Utility.PolarPoint(array('d', p4), radians(90), float(aba)-float(espessura))
p6 = acad.doc.Utility.PolarPoint(array('d', p5), radians(180), float(espessura))

pontos = [p1[0] , p1[1], p2[0] , p2[1], p3[0] , p3[1], p4[0] , p4[1] ,p5[0] , p5[1] ,p6[0] , p6[1]]
pontos_1 = array('d', pontos)

poli = desenho.AddLightweightPolyline(pontos_1)
poli.Closed = 1

a = array('c',str(poli)) # first attempt

aa = numpy.array(poli, dtype='O') # second attempt

g = desenho.AddRegion(aa)

solido = poli.AddExtrudedSolid(g, 1000, 0)

How to use GetXData?

GetXData AppName, XDataType, XDataValue
need two parameters return,how to use ?

_ctypes.COMError: -2147467262

Hi Roman,
First of all - thank you so much for this library. It is working great and allows me to do what i wanted just in Python.
I wrote a simple script (with gui) and it worked well on my machine, but after compiling i tried it on two different machines and received an error. Here is a version of the error from each of the machines:

  1. _ctypes.COMError: (-2147467262, 'No such interface supported', (None, None))
  2. _ctypes.COMError: (-2147467262, '\xfe\xfe\xee\xee\xf9\xf7 \xee\xf1\xe5\xe2 \xe6\xe4 \xe0\xe9\xf0\xe5 \xf0\xfa\xee\xea', (None, None, None, 0, None))

Here is the code i used:

import sys
import pygtk
if not sys.platform == 'win32':
    pygtk.require('2.0')

import gtk,gobject,time
import os.path
import datetime
from pyautocad import Autocad, utils
from pyautocad.contrib.tables import Table

now = datetime.datetime.now()
today_date = str(now.year) + str(now.month) + str(now.day) + "_" + str(now.hour) + "-" + str(now.minute)
acad = Autocad()

def set_file_name(self):
#This method checks the existance of an XLS file, and allows the user to overwrite it, 
#or use a different file.
    tableFilename = raw_input("Enter table name: ")
    tableFilename = tableFilename + ".xls"
    if os.path.isfile(tableFilename):
        fileoverwrite = 'n'
        while (fileoverwrite != 'y' or fileoverwrite != 'Y' or (os.path.isfile(tableFilename))):
            fileoverwrite = raw_input("File " + tableFilename + " exist. Overwrite (y/n)?")
            if fileoverwrite == 'y' or fileoverwrite == 'Y':
                break
            elif fileoverwrite == 'n' or fileoverwrite == 'N':
                tableFilename = raw_input("Enter table name: ")
                tableFilename = tableFilename + ".xls"
                if os.path.isfile(tableFilename):
                    continue
                else:
                    break
            else:
                print "Goodbye!"
                sys.exit(0)
    return tableFilename            


def line_lengths_excel(filename, draw_units):
# This function iterate over all the layers in the opened DWG and write sum of line lengths of each layer into one MS-Excel sheet.
# Parameters needed:
#1. Name of an MS-Excel file (doesn't have to exist)
#2. Units of the drwaing

        tableFilename = filename + '.xls'#set_file_name(self)
        table = Table()
        layers = []
        total_length = []
        units_scale = {"m":1, "cm":100, "mm":1000}
        units = draw_units #raw_input("Enter the used units for scaling(m/cm/mm): ")
        scale = units_scale[units]
        acad.prompt("Creating a table of line lengths")
        # value = 0.0
        for line in acad.iter_objects('line'):
            # pbar.set_fraction(value)
            # value = value + 0.01
            l1 = line.Length
            #print line.Layer
            if line.Layer in layers:
                i = layers.index(line.Layer)
                total_length[i] += l1
            else:
                layers.append(line.Layer)
                total_length.append(l1)
        print layers
        print total_length
        # Add data to table
        table.writerow(["COMPANY NAME", "Lines Lengths, Created:"+today_date])
        table.writerow(["Layer", "Length [" + units+"]"])
        for i in range(len(layers)):
            table.writerow([layers[i], total_length[i]])
        # Save table in xls
        table.save(tableFilename, 'xls')
        # raw_input("Press Enter to continue...")

def count_blocks_excel(filename):
# This function iterate over all the layers in the opened DWG and summing up all the blocks in the file into one MS-Excel sheet.
# Parameters needed:
#1. Name of an MS-Excel file (doesn't have to exist)

        tableFilename = filename + '.xls'#set_file_name(self)
        table = Table()
        block_list = []
        block_layer = []
        total_blocks = []
        acad.prompt("Creating a table of blocks count")
        for layer in acad.iter_layouts():
            for block in acad.iter_objects('block'):
                b1 = block
                if block.name in block_list:
                    i = block_list.index(block.name)
                    total_blocks[i] += 1
                else:
                    block_list.append(block.name)
                    block_layer.append(block.Layer)
                    total_blocks.append(1)
        print block_list
        print total_blocks
        # Add data to table
        table.writerow(["Layer","Block", "Amount"])
        for i in range(len(block_list)):
            table.writerow([block_layer[i], block_list[i], total_blocks[i]])
        # Save table in xls
        table.save(tableFilename, 'xls')
        # raw_input("Press Enter to continue...")

class PyAPP():
    def __init__(self):
        self.window = gtk.Window()
        self.window.set_title("Automating AutoCAD Calculations")

        self.create_widgets()
        self.connect_signals()
        try:
            self.window.set_icon_from_file("Logo25.png")
        except Exception, e:
            print e.message
            sys.exit(1)
        self.window.show_all()
        gtk.main()

    def create_widgets(self):
        self.vbox = gtk.VBox(spacing=10)

        self.hbox_0 = gtk.HBox(spacing=10)      
        self.company_logo = gtk.Image()
        self.company_logo.set_from_file("company25mm90.png")
        self.hbox_0.pack_start(self.company_logo)

        self.hbox_1 = gtk.HBox(spacing=10)
        self.label = gtk.Label("File Name: ")
        self.hbox_1.pack_start(self.label)
        self.entry = gtk.Entry()
        self.hbox_1.pack_start(self.entry)
        self.unitsLabel = gtk.Label("DWG units: ")
        self.hbox_1.pack_start(self.unitsLabel)
        self.units = gtk.combo_box_new_text()
        self.units.append_text('m')
        self.units.append_text('cm')
        self.units.append_text('mm')
        self.units.set_active(1)
        self.hbox_1.pack_start(self.units)

        self.hbox_2 = gtk.HBox(spacing=10)
        self.bLineLength = gtk.Button("Sum Lines Lengths in a DWG to MS-Excel")
        self.hbox_2.pack_start(self.bLineLength)
        self.bBlocksCount = gtk.Button("Count Blocks in a DWG to MS-Excel")
        self.hbox_2.pack_start(self.bBlocksCount)

        self.hbox_3 = gtk.HBox(spacing=10)
        self.pbar = gtk.ProgressBar()
        self.hbox_3.pack_start(self.pbar)
        self.button_exit = gtk.Button("Exit")
        self.hbox_3.pack_start(self.button_exit)

        self.hbox_4 = gtk.HBox(spacing=10)
        self.se_logo = gtk.Image()
        self.se_logo.set_from_file("Logo25.png")
        self.hbox_4.pack_start(self.se_logo)
        self.se_label = gtk.Label("(2013)")
        self.hbox_4.pack_start(self.se_label)

        self.vbox.pack_start(self.hbox_0)
        self.vbox.pack_start(self.hbox_1)
        self.vbox.pack_start(self.hbox_2)
        self.vbox.pack_start(self.hbox_3)
        self.vbox.pack_start(self.hbox_4)

        self.window.add(self.vbox)

    def connect_signals(self):
        self.filename = self.entry.set_text('temp'+today_date)
        self.button_exit.connect("clicked", self.callback_exit)
        self.bLineLength.connect('clicked', self.callback_lines_lengths)
        self.bBlocksCount.connect('clicked', self.callback_blocks_count)    

    def callback_lines_lengths(self, widget, callback_data=None):
        filename = self.entry.get_text()
        draw_units = self.units.get_active_text()
        line_lengths_excel(filename, draw_units)

    def callback_blocks_count(self, widget, callback_data=None):
        filename = self.entry.get_text()
        count_blocks_excel(filename) 

    def callback_exit(self, widget, callback_data=None):
        gtk.main_quit()


if __name__ == "__main__":
    app = PyAPP()

and a trace back attached as an image.

Do you have any idea what went wrong?

Thanks,

Shai.
AAC_SE_Error 1

howto polyline?

m.AddPolyline((APoint(0,0),APoint(-1000,-1000),APoint(5000,-5000)))
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\P1\AppData\Local\Programs\Python\Python36\lib\site-packages\comtypes\client\lazybind.py", line 182, in caller
return self._comobj._invoke(descr.memid, descr.invkind, 0, *args)
File "C:\Users\P1\AppData\Local\Programs\Python\Python36\lib\site-packages\comtypes\automation.py", line 729, in _invoke
dp, var, None, argerr)
_ctypes.COMError: (-2147352567, 'Ошибка.', (None, None, None, 0, None))

Changing units

How do I change units in pyautocad. Even if I'm changing it in the autocad to feets and inches, once I run the code, It makes it back to decimal.

Error when trying example usage.

My autocad object has created well but getting error on acad.prompt(). Following is the error :

acad.prompt("Hello")
Hello
Traceback (most recent call last):
File "", line 1, in
File "c:\users\snehal\appdata\local\temp\easy_install-lipjer\pyautocad-0.2.0-py2.7-win32.egg.tmp\pyautocad\api.py", line 162, in prompt
File "c:\users\snehal\appdata\local\temp\easy_install-lipjer\pyautocad-0.2.0-py2.7-win32.egg.tmp\pyautocad\api.py", line 74, in doc
File "c:\users\snehal\appdata\local\temp\easy_install-lipjer\pyautocad-0.2.0-py2.7-win32.egg.tmp\pyautocad\api.py", line 63, in app
File "C:\Python27\lib\site-packages\comtypes-1.1.3-py2.7.egg\comtypes\client_init_.py", line 173, in GetActiveObject
clsid = comtypes.GUID.from_progid(progid)
File "C:\Python27\lib\site-packages\comtypes-1.1.3-py2.7.egg\comtypes\GUID.py", line 78, in from_progid
_CLSIDFromProgID(unicode(progid), byref(inst))
File "_ctypes/callproc.c", line 950, in GetResult
WindowsError: [Error -2147221005] Invalid class string

Please help me solving this issue . I need it on urgent basis

(-2147352567, '예외가 발생했습니다.', ('키를 찾을 수 없습니다.', 'AutoCAD.Application', 'C:\\Program Files\\Autodesk\\AutoCAD 2020\\HELP\\OLE_ERR.CHM', -2145386476, None))

I can't run an example file with the following error messages.

COMError Traceback (most recent call last)
Cell In[7], line 27
25 p2=APoint(p2x[j],p2y[j]+z)
26 line1=acad.model.AddLine(p1,p2)
---> 27 line1.layer='Beam_LSection'
28 if j >= 8:
29 line1.layer='Text'

File ~\anaconda3\lib\site-packages\comtypes\client\lazybind.py:218, in Dispatch.setattr(self, name, value)
216 descr = put or putref
217 if descr.cParams == 1:
--> 218 self._comobj._invoke(descr.memid, descr.invkind, 0, value)
219 return
220 raise AttributeError(name)

File ~\anaconda3\lib\site-packages\comtypes\automation.py:728, in IDispatch._invoke(self, memid, invkind, lcid, *args)
725 dp.rgdispidNamedArgs = pointer(DISPID(DISPID_PROPERTYPUT))
726 dp.rgvarg = array
--> 728 self.__com_Invoke(memid, riid_null, lcid, invkind,
729 dp, var, None, argerr)
730 return var._get_value(dynamic=True)

COMError: (-2147352567, '예외가 발생했습니다.', ('키를 찾을 수 없습니다.', 'AutoCAD.Application', 'C:\Program Files\Autodesk\AutoCAD 2020\HELP\OLE_ERR.CHM', -2145386476, None))

Plot automation

I'm working on a project of plan plotting automation with python, I was able to do it with pywin32 but I couldn't do it with pyautocad. The problem itself is that I need a point of only 2 coordinates for the plotting window, APoint uses three dimensions, is there any alternative to solve this problem?

acad.ActiveDocument.ActiveLayout.SetWindowToPlot(Point1, Point2)
Point1 and Point 2 must be only x , y coordinates.

Open DWG files and manipulate them

I am trying to figure out if it is possible to open multiple already existing dwg files through pyautocad and manipulate them to create a single dwg file. Basically, I am trying to figure out if I can take various drawings of different length walls and manipulate those walls to create a single room. I am trying to automate this process as each wall is already drawn and it is tedious to pull in each wall every time I go to draw a room. Does pyautocad support something like this? I was unable to find anything in the documentation on opening and manipulating previously created DWG files.

Possible Typo in pyautocad-0.2.0.zip and pyautocad-0.2.0.win32.exe

Just installed the pyautocad (and github to make this issue) this afternoon and when running a test for: data = Table.data_from_file('data.xls')
I kept getting an error message for xrange not existing. It was fixed when I deleted an x within the table.py file on lines 163 and 165. I've never used github so I don't have the experience for proposing actions/fixes but I hope someone can use this information to fix the error for other newcomers like me.

MacOS

Is possible to run pyautocad in a mac?
Im trying and I get this error:

`
Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

import pyautocad
Traceback (most recent call last):
File "", line 1, in
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyautocad/init.py", line 15, in
from pyautocad.api import *
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyautocad/api.py", line 16, in
import comtypes
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/comtypes/init.py", line 23, in
from _ctypes import COMError
ImportError: cannot import name 'COMError'`

can not read attributes from block reference

I'm trying to read block attributes:

from pyautocad import Autocad
acad =  Autocad()       

Reading other properties works fine:

In [89]: b.InsertionPoint
Out[89]: (3764.4951495785735, 745.3710248379173, 0.0)

However, when I want to query the attributes (which I'm actually interested in), I get an error message:

In [88]: b.GetAttributes()
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-88-a01693316a19> in <module>()
----> 1 b.GetAttributes()

C:\ProgramFiles\Python27\lib\site-packages\comtypes\automation.pyc in __ctypes_from_outparam__(self)
    440     def __ctypes_from_outparam__(self):
    441         # XXX Manual resource management, because of the VARIANT bug:
--> 442         result = self.value
    443         self.value = None
    444         return result

C:\ProgramFiles\Python27\lib\site-packages\comtypes\automation.pyc in _get_value(self, dynamic)
    391             return value
    392         elif self.vt & VT_ARRAY:
--> 393             typ = _vartype_to_ctype[self.vt & ~VT_ARRAY]
    394             return cast(self._.pparray, _midlSAFEARRAY(typ)).unpack()
    395         else:

Did some research on Google, but my knowledge of COM is just too low to help myself here..

Pyautocad: error using pyautocad library on windows (python 3.8)

Good moning,

I’m trying using pyautocad library in python 3.8 on windows with the following example code taken from a tutorial:
import pyautocad acad = pyautocad.Autocad() print(acad.doc.Name) from pyautocad import APoint point1 = APoint(100.0,100.0) circle1 = acad.model.AddCircle(point1,100) circle1.Color = 10 print("current layer: " + str(circle1.Layer)) print("current linetype: " + str(circle1.Linetype)) print("current linetype scale: " + str(circle1.LinetypeScale)) print("current line weight: " + str(circle1.Lineweight)) print("current thickness: " + str(circle1.Thickness)) print("current material:" + str(circle1.Material)) circle1.Layer = "circles" circle1.Color = 256 circle2 = acad.model.AddCircle(APoint(200.0,200.0),100) circle3 = acad.model.AddCircle(APoint(300.0,300.0),100) for obj in acad.iter_objects(): print(obj)

But I obtain the following error and I don’t understand how to solve it:

python pyAutocadTest.py Traceback (most recent call last): File "pyAutocadTest.py", line 6, in <module> print(acad.doc.Name) File "C:\Users\3bMeteo\anaconda3\lib\site-packages\pyautocad\api.py", line 74, in doc return self.app.ActiveDocument File "C:\Users\3bMeteo\anaconda3\lib\site-packages\pyautocad\api.py", line 63, in app self._app = comtypes.client.GetActiveObject('AutoCAD.Application', dynamic=True) File "C:\Users\3bMeteo\anaconda3\lib\site-packages\comtypes\client\__init__.py", line 180, in GetActiveObject obj = comtypes.GetActiveObject(clsid, interface=interface) File "C:\Users\3bMeteo\anaconda3\lib\site-packages\comtypes\__init__.py", line 1245, in GetActiveObject oledll.oleaut32.GetActiveObject(byref(clsid), None, byref(p)) File "_ctypes/callproc.c", line 948, in GetResult OSError: [WinError -2147221021] Operazione non disponibile

Can I ask if someone has a solution?

Thank you in advance

Best Regard

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.