AutoCAD Map 3D Forum
Welcome to Autodesk’s AutoCAD Map 3D Forums. Share your knowledge, ask questions, and explore popular AutoCAD Map 3D topics.
abbrechen
Suchergebnisse werden angezeigt für 
Anzeigen  nur  | Stattdessen suchen nach 
Meintest du: 

AUTOCAD and PYTHON, OSERROR [WinError -2147221005]

1 ANTWORT 1
Antworten
Nachricht 1 von 2
adeboerNRXXE
108 Aufrufe, 1 Antwort

AUTOCAD and PYTHON, OSERROR [WinError -2147221005]

Hi there,

 

I was trying to access autocad from python and could not load due to a windows error. 

 

I was trying to access the file, then add a layer. Than based on the added layer create an offset into both directions. Make a new layer for the offset of the line. And then write the autocad file to a new file. Right now I get an error, I tried to move the registry key from local machine to current user, but it seemed like that it did not solve the problem. Do you know what could be the problem?


from pyautocad import Autocad, APoint
import geopandas as gpd
from shapely.geometry import LineString

def add_shapefile_layer_and_offset(dwg_file_path, shapefile_path, offset_distance, output_file_path):
# Initialize AutoCAD
acad = Autocad(create_if_not_exists=True)
acad.prompt("AutoCAD script started\n")
print("Initialized AutoCAD")

# Open the DWG file
acad.app.Documents.Open(dwg_file_path)
doc = acad.app.ActiveDocument
modelspace = doc.ModelSpace
print(f"Opened DWG file: {dwg_file_path}")

# Load the shapefile
gdf = gpd.read_file(shapefile_path)
print(f"Loaded shapefile: {shapefile_path}")

# Add the original layer with specific attributes if it doesn't exist
layer_name = '_scritte_sottile'
try:
layer = doc.Layers.Item(layer_name)
print(f"Layer '{layer_name}' already exists")
except:
layer = doc.Layers.Add(layer_name)
layer.Color = 255
layer.Linetype = 'trattopuntox2'
layer.Lineweight = 0.05
print(f"Created new layer: {layer_name}")

# Add lines from the shapefile to the DWG
for geom in gdf.geometry:
if isinstance(geom, LineString):
coords = list(geom.coords)
points = [APoint(x, y) for x, y in coords]
polyline = modelspace.AddPolyline(points)
polyline.Layer = layer_name
print(f"Added polyline to layer '{layer_name}'")

# Create offsets of the lines in the new layer
for entity in modelspace:
if entity.Layer == layer_name and entity.ObjectName == 'AcDbPolyline':
offset_entities = entity.Offset(offset_distance)
print(f"Created offsets for entity in layer '{layer_name}'")

# Add new layers for the offsets with specific attributes if they don't exist
offset_layer = '_tracciolino'
try:
offset_layer_obj = doc.Layers.Item(offset_layer)
print(f"Offset layer '{offset_layer}' already exists")
except:
offset_layer_obj = doc.Layers.Add(offset_layer)
offset_layer_obj.Color = 30
offset_layer_obj.Linetype = 'Continuous'
offset_layer_obj.Lineweight = 0.09
print(f"Created new offset layer: {offset_layer}")

# Add offset lines to the new layers
for offset_entity in offset_entities:
offset_entity.Layer = offset_layer
print(f"Added offset entity to layer '{offset_layer}'")

# Save the modified DWG file
doc.SaveAs(dwg_file_path)
print(f"Saved modified DWG file: {dwg_file_path}")

dwg_file_path = r'S:\progetti\1173_STRADE VICINALI MODIGLIANA_Ord. 13-23_001731_Varianti TREBBIO\1173_Cartografia\1173_curve_di_livello\1173_FUCA\1173_FUCA.dwg'
shapefile_path = r'S:\progetti\1173_STRADE VICINALI MODIGLIANA_Ord. 13-23_001731_Varianti TREBBIO\1173_Cartografia\1173_curve_di_livello\1173_FUCA\1173_FUCA.shp'
offset_distance = 1.5
output_file_path = r'S:\progetti\1173_STRADE VICINALI MODIGLIANA_Ord. 13-23_001731_Varianti TREBBIO\1173_Cartografia\1173_curve_di_livello\1173_FUCA\1173_FUCA_planimetria.dwg'

add_shapefile_layer_and_offset(dwg_file_path, shapefile_path, offset_distance, output_file_path)

print(f"Shapefile '{shapefile_path}' added as layer '_scritte_sottile' and offset by {offset_distance} meters in both directions for file '{dwg_file_path}'.")

 

adeboerNRXXE_0-1733909258185.png

AutoCAD script started

 
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
File ~\AppData\Local\anaconda3\Lib\site-packages\pyautocad\api.py:63, in Autocad.app(self)
     62 try:
---> 63     self._app = comtypes.client.GetActiveObject('AutoCAD.Application', dynamic=True)
     64 except WindowsError:

File ~\AppData\Local\anaconda3\Lib\site-packages\comtypes\client\__init__.py:166, in GetActiveObject(progid, interface, dynamic)
    157 """Return a pointer to a running COM object that has been
    158 registered with COM.
    159 
   (...)
    164 'dynamic=True' will return a dynamic dispatch object.
    165 """
--> 166 clsid = GUID.from_progid(progid)
    167 if dynamic:

File ~\AppData\Local\anaconda3\Lib\site-packages\comtypes\GUID.py:73, in GUID.from_progid(cls, progid)
     72 inst = cls()
---> 73 _CLSIDFromProgID(str(progid), byref(inst))
     74 return inst

File _ctypes/callproc.c:1008, in GetResult()

OSError: [WinError -2147221005] Stringa dell'interfaccia non valida

During handling of the above exception, another exception occurred:

OSError                                   Traceback (most recent call last)
Cell In[1], line 74
     71 offset_distance = 1.5
     72 output_file_path = r'S:\progetti\1173_STRADE VICINALI MODIGLIANA_Ord. 13-23_001731_Varianti TREBBIO\1173_Cartografia\1173_curve_di_livello\1173_FUCA\1173_FUCA_planimetria.dwg'
---> 74 add_shapefile_layer_and_offset(dwg_file_path, shapefile_path, offset_distance, output_file_path)
     76 print(f"Shapefile '{shapefile_path}' added as layer '_scritte_sottile' and offset by {offset_distance} meters in both directions for file '{dwg_file_path}'.")

Cell In[1], line 8, in add_shapefile_layer_and_offset(dwg_file_path, shapefile_path, offset_distance, output_file_path)
      5 def add_shapefile_layer_and_offset(dwg_file_path, shapefile_path, offset_distance, output_file_path):
      6     # Initialize AutoCAD
      7     acad = Autocad(create_if_not_exists=True)
----> 8     acad.prompt("AutoCAD script started\n")
      9     print("Initialized AutoCAD")
     11     # Open the DWG file

File ~\AppData\Local\anaconda3\Lib\site-packages\pyautocad\api.py:162, in Autocad.prompt(self, text)
    159 """ Prints text in console and in `AutoCAD` prompt
    160 """
    161 print(text)
--> 162 self.doc.Utility.Prompt(u"%s\n" % text)

File ~\AppData\Local\anaconda3\Lib\site-packages\pyautocad\api.py:74, in Autocad.doc(self)
     71 @property
     72 def doc(self):
     73     """ Returns `ActiveDocument` of current :attr:`Application`"""
---> 74     return self.app.ActiveDocument

File ~\AppData\Local\anaconda3\Lib\site-packages\pyautocad\api.py:67, in Autocad.app(self)
     65         if not self._create_if_not_exists:
     66             raise
---> 67         self._app = comtypes.client.CreateObject('AutoCAD.Application', dynamic=True)
     68         self._app.Visible = self._visible
     69 return self._app

File ~\AppData\Local\anaconda3\Lib\site-packages\comtypes\client\__init__.py:255, in CreateObject(progid, clsctx, machine, interface, dynamic, pServerInfo)
    229 def CreateObject(
    230     progid: _UnionT[str, Type[CoClass], GUID],  # which object to create
    231     clsctx: Optional[int] = None,  # how to create the object
   (...)
    237     ] = None,  # server info struct for remoting
    238 ) -> Any:
    239     """Create a COM object from 'progid', and try to QueryInterface()
    240     it to the most useful interface, generating typelib support on
    241     demand.  A pointer to this interface is returned.
   (...)
    253     You can also later request to receive events with GetEvents().
    254     """
--> 255     clsid = GUID.from_progid(progid)
    256     logger.debug("%s -> %s", progid, clsid)
    257     if dynamic:

File ~\AppData\Local\anaconda3\Lib\site-packages\comtypes\GUID.py:73, in GUID.from_progid(cls, progid)
     71         return cls(progid)
     72     inst = cls()
---> 73     _CLSIDFromProgID(str(progid), byref(inst))
     74     return inst
     75 else:

File _ctypes/callproc.c:1008, in GetResult()

OSError: [WinError -2147221005] Stringa dell'interfaccia non valida
Beschriftungen (4)
1 ANTWORT 1
Nachricht 2 von 2
O_Eckmann
als Antwort auf: adeboerNRXXE

Hi,

 

Managing Geospatial API with python isn't very easy. (generally speaking, managing AutoCAD with Python isn't the easiest way).

Perhaps, you could look at this blog : https://pyarx.blogspot.com/2023/09/geopandas-with-python-and-autocad.html 

 

Olivier

Olivier Eckmann

EESignature

Sie finden nicht, was Sie suchen? Fragen Sie die Community oder teilen Sie Ihr Wissen mit anderen.

In Foren veröffentlichen  

Autodesk Design & Make Report