Introducing Python for CAD
15 Jun, 2022By: Andrew G. Roe
CAD Programming: Open-source language offers intriguing features for CAD programmers.
Of all the programming options available to CAD programmers, one of the more intriguing is Python. An open-source platform named after the British comedy troupe Monty Python, Python is a high-level, interpreted language, meaning the code is relatively easy to decipher and the development process is often faster than that of other languages.
In this article, we’ll take a brief tour of Python, looking at some key features that might be helpful to CAD programmers. We’ll also look at some of the different flavors, or implementations, of Python. We’ll then circle back and see how to use Python in conjunction with Dynamo, a tool we explored in previous articles. The terminology and nuances can be a bit confusing at first, but hang on through the tour to see what Python has to offer.
Why Learn Python?
As a high-level language, Python uses recognizable English keywords instead of cryptic phrases that only a computer could love. Its formatting is relatively simple, with minimal use of punctuation, curly brackets, and other symbols commonly used in other languages. For both new and experienced programmers, this makes Python fairly easy to learn.
Because it is an interpreted language, Python code does not need to be compiled before running — a considerable time saver during program development. The interpreter can be used interactively, allowing you to see results as you type code.
With high-level data structures such as flexible arrays and dictionaries, Python can be used as an extension language for customizable applications such as AutoCAD and MicroStation. In fact, the extensibility of Python allows you to interact with code written in totally different languages, such as C/C++ or Java. Python also lets you build modules that can be reused in other Python programs.
As an open-source language, Python is free to download, use, and distribute. Documentation is readily available on the Python website, along with a plethora of examples. Other websites and videos scattered across the internet offer additional examples and guidance.
Versions and Implementations
Just as many commercial software vendors offer different versions of their products, various open-source communities have developed different implementations of Python. The standard implementation, CPython is generally referred to simply as Python. Written in C, as implied by the name, it is considered the baseline implementation, most aligned with Python standards.
IronPython is an implementation of Python based on the .NET runtime. You can load .NET assemblies into IronPython programs using an object-oriented syntax. You can also compile IronPython code into an assembly and run it standalone or invoke it from other languages.
PyPy is a variation developed to improve performance using just-in-time (JIT) compilation. By compiling Python code into machine language behind the scenes, PyPy can achieve significant speed gains on large programs.
For AutoCAD programmers, pyautocad is a Python library geared toward writing ActiveX Automation scripts for AutoCAD. It is helpful for working with coordinates, object iteration and searching, and data import and export. Certain Autodesk products, such as Civil 3D and Revit, also include a built-in version of Python in the Dynamo environment. More on this later.
On the Bentley side, Python developer shells are available for certain vertical applications. For example, Python-based software development kits (SDKs) are available for LumenRT, Bentley’s visualization and reality modeling software, and PLAXIS, a geotechnical analysis product. The Bentley visualization and geotechnical analysis user communities provide more information.
Several other flavors of Python are also available. The Python Package Index (PyPI) is a repository of various Python implementations.
Installing and Starting Python
To use Python outside of the Dynamo environment, first install it on your computer. A small fraction of Windows PCs have Python pre-installed, but chances are you will need to download and install it. To check to see if you already have it, enter python in a Command line window. If you see a response from a Python interpreter, you have the version identified in the initial display. If you need to install Python, you can find the latest version on the Python downloads page and follow the instructions to install it.
Once you install Python, you should see it listed on your startup menu, or you can invoke it from the Command line. The Python interpreter does not have a fancy interface, but the shell provides the basic tools to get started.
Click to enlarge.
Syntax Fundamentals
Before learning how to write code in Python, check out the interactive nature of the interpreter by typing in a mathematical expression, such as 2+2, right after the Command prompt, which is >>>. Python displays the answer on the next line.
Click to enlarge.
While Python is a high-level language that uses common English phrases, there are still some rules to follow. We won’t cover them all here, as the website includes thorough documentation, but here are some highlights:
· As you’ve seen, you can type a numerical expression and the interpreter writes the value. The mathematical operators +, -, *, and / work just like in most other languages.
· Strings, or text, can be enclosed in single quotes (‘Hello’) or double quotes (“Hello”) with the same result.
· Lists can be written as a series of comma-separated values between square brackets. For example: Layers = [0, 1, 2, 10]
· Functions perform specific actions. For example, the print() function writes the value of the argument(s) enclosed by parentheses.
Click to enlarge.
· Methods are functions associated with a particular object. Many built-in data types come with pre-defined methods, and you can also create your own methods.
· A variety of logic and flow-control tools are available, such as if, for, and while statements.
Python code can be written with any text editor, though you may benefit by using more enhanced text editors like Visual Studio Code or Notepad++. From the Python shell interface, you can save your code for reuse by clicking File | Save and giving your file a name.
Click to enlarge.
And Now for Something Completely Different. . . Python and Dynamo
(Did you catch the Monty Python reference in the heading?) With some Python fundamentals covered, we can now turn to what Python has to offer CAD programmers. For AutoCAD programmers, one way to leverage Python code is via the Dynamo environment.
In previous articles, we learned how to use Dynamo to create a line, as well as how to use code blocks to simplify Dynamo scripts. By combining Python and Dynamo, you can combine tools from both environments to build custom applications. Autodesk products aid this process by including a built-in version of Python within Dynamo.
In Civil 3D 2022, both the CPython and the IronPython interpreters are available. This is primarily for compatibility reasons, as CPython is currently in version 3, while IronPython is only available in version 2. The version of Python available in other Autodesk products may vary by version, but the ability to access Python within the Dynamo environment has been a significant step for CAD programmers.
In our first Dynamo article, we demonstrated how to create an AutoCAD line using pre-defined point coordinates. The Dynamo graph looked like this:
Click to enlarge.
Instead of using input nodes for each coordinate value, you can use a Python script to provide the same input for some or all of the nodes. To demonstrate, we’ll establish the Y2 value using Python:
1. Open a Civil 3D (or Revit) drawing and create a Dynamo session similar to the one above. (Refer to the first article for a recap of those steps. If you already worked through that example, you can reuse your script.)
2. In the Search box of the Library pane in Dynamo, type “Python” to access the Python environment. Click Python Script to add this node to your workspace.
Click to enlarge.
3. Double-click in the lower portion of the Python Script node to open the Python Script editor. Notice near the lower-left portion of the window a drop-down showing the two versions of Python available. For this example, we’ll use CPython.
Click to enlarge.
4. The Python Script editor includes numerous lines of boiler-plate code that you can ignore for now. Change the last line to read as follows:
OUT = Y2
5. Just above last line, insert a new line as follows:
Y2 = 7
6. Connect the output of the Python Script node to the Y-value in the
Point.ByCoordinates node. The modified Dynamo graph should look like this:
Click to enlarge.
7. Click Run in the lower-left corner of the Dynamo window to run your script. (You can skip this step if you’re running Dynamo in Automatic mode.) You should see a new line drawn with the Y-value generated by Python.
While this is a greatly simplified example for brevity, you can see how you can use Python to provide additional power to your programming toolbox. With Python’s more robust features such as logic and flow-control, along with Dynamo’s graphic environment for creating programs quickly, the sky is the limit for creating custom applications.
We’ll continue to explore how to use Dynamo, Python, and other tools in future articles. If you have specific ideas for programming topics, feel free to drop us an email.
About the Author: Andrew G. Roe
· See contents by Andrew G. Roe