Monday, July 6, 2009

AutoCAD and Python Part 2

In Part 1 I talked about my search to replace AutoLISP with another customization method. Today I am sharing my success controlling AutoCAD (which I have been using for fifteen years) with Python (which I have never used).

Obviously I have AutoCAD running. So the next item of business was to install Python. I got the ActivePython installation package from ActiveState and installed it. Then I got the win32all package from Sourceforge. I downloaded it in zip file format, extracted the zip file, and double-clicked first on setup.py, then on pywin32_postinstall.py. I was just guessing, so I dont' know if the second one was necessary. Then I opened the Python Interactive Shell from the Windows Start Programs menu and pasted the Tim Riley snippet on my Part 1 post line by line into the shell. What do you know if it didn't actually echo "Hello from Python" to my AutoCAD Civil 3D command line!


import win32com.client
acad = win32com.client.Dispatch("AutoCAD.Application")
doc = acad.ActiveDocument
doc.Utility.Prompt("Hello from Python\n")


Now let's try combining that with some of the experimentation I tried at my Accessing the AutoCAD Object Model post. Let's go back to that Python Interactive shell.


doc.ModelSpace.AddCircle


Nope. It's an error. And I can't find the solution today.  Please leave a comment if you know how to get further than this in AutoCAD with Python.  I am very interested.

3 comments:

Unknown said...

Hi all, I am good in AutoLisp and VBA, but new to Python development for Autocad, can anyone giude how load and run[invoke] .py files from autocad command line.

Thanks
Sadanand

Unknown said...

Hi all, I am good in AutoLisp and VBA, but new to Python development for Autocad, can anyone giude how load and run[invoke] .py files from autocad command line.

Thanks
Sadanand

Thomas Gail Haws said...

Sadanad,
I think I missed your comment. You can use the (startapp) function to "open" any file on the Windows system. If you have .py files associated properly in Windows to automatically run when you double-click them in Windows Explorer, they should do what you want when you invoke them with (startapp). I use this strategy to open spreadsheets by calling just the spreadsheet file name and letting Windows association handle the call to the spreadsheet program of choice.
Tom