Introducing Python for CAD | Cadalyst



June 15, 2022

By: Andrew G. Roe



CAD programming: The open source language offers intriguing features for CAD programmers.

Of all the programming options available to CAD programmers, one of the most intriguing is Python. An open-source platform named after the British comedy troupe Monty Python, Python is a high-level interpreted language, which means that the code is relatively easy to crack and the development process is often faster than that of software. other languages.

In this article, we’ll take a quick tour of Python, looking at some key features that CAD programmers might find useful. We’ll also look at some of the different versions, or implementations, of Python. Then we’ll come back and see how to use Python in conjunction with Dynamo, a tool we’ve explored in previous articles. The terminology and nuances can be a bit confusing at first, but wait 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 might like. Its formatting is relatively simple, with minimal use of punctuation, braces, and other symbols commonly used in other languages. For both new and experienced programmers, this makes Python quite easy to learn.

Because it is an interpreted language, Python code does not need to be compiled before running – a huge time saver when developing the program. The interpreter can be used interactively, allowing you to see results as you type code.

With high-level data structures like flexible arrays and dictionaries, Python can be used as an extension language for customizable applications like AutoCAD and MicroStation. In fact, Python’s extensibility allows you to interact with code written in entirely different languages, such as C/C++ or Java. Python also lets you create modules that can be reused in other Python programs.

As an open source language, Python can be downloaded, used and distributed for free. 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 usually simply called Python. Written in C, as its name suggests, it is considered the most basic, standards-aligned Python implementation.

IronPython is a Python implementation based on the .NET runtime. You can load .NET assemblies into IronPython programs using object-oriented syntax. You can also compile IronPython code into an assembly and run it standalone or invoke it from other languages.

Python is a variant developed to improve performance by using just-in-time (JIT) compilation. By compiling Python code to machine language behind the scenes, PyPy can achieve significant speed gains on large programs.

For AutoCAD programmers, pyautocad is a Python library geared towards writing ActiveX automation scripts for AutoCAD. It is useful for working with coordinates, iterating and finding objects, and importing and exporting data. Some Autodesk products, such as Civil 3D and Revit, also include an integrated version of Python within the Dynamo environment. More on that later.

On the Bentley side, Python development shells are available for some vertical applications. For example, Python-based software development kits (SDKs) are available for LumenRTBentley’s reality visualization and modeling software, and PLAXIS, a geotechnical analysis product. The Bentley visualization and geotechnical analysis user communities provide more information.

Several other versions 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. Python comes pre-installed on a small portion of Windows PCs, but you’ll likely need to download and install it. To check 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’ve installed Python, you should see it listed in your start menu, or you can invoke it from the command line. The Python interpreter doesn’t have a fancy interface, but the shell provides the basic tools to get started.

Python

Click to enlarge.

Syntax Fundamentals

Before learning to write code in Python, check the interactive nature of the interpreter by typing a mathematical expression, such as 2+2, right after the command prompt, which is >>>. Python displays the response on the next line.

Python

Click to enlarge.

Although Python is a high-level language that uses common English expressions, there are still a few rules to follow. We won’t cover them all here, because the website includes extensive documentation, but here are some highlights:

  • As you have seen, you can type a numeric expression and the interpreter writes the value. The mathematical operators +, -, * and / work 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 ​​in square brackets. For instance: Layers = [0, 1, 2, 10]

  • Functions perform specific actions. For example, the print() function writes the value of the argument(s) in parentheses.

Python

Click to enlarge.

  • Methods are functions associated with a particular object. Many built-in data types come with predefined methods, and you can also create your own methods.

  • A variety of logic and flow control tools are available, such as if, forand while statements.

Python code can be written with any text editor, although you can benefit from more advanced text editors like Visual Studio Code or Notepad++. From the Python shell interface, you can save your code for reuse by clicking File | to safeguard and name your file.

Python

Click to enlarge.

And now for something completely different. . . Python and Dynamo

(Did you catch the Monty Python reference in the header?) 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 through 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 create custom applications. Autodesk products facilitate this process by including an integrated version of Python in Dynamo.

In Civil 3D 2022, CPython and IronPython interpreters are available. This is mainly 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 being able to access Python in the Dynamo environment was a milestone for CAD programmers.

In our first Dynamo article, we showed how to create an AutoCAD line using predefined point coordinates. The Dynamo chart looked like this:

Python

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 set the Y2 value using Python:

1. Open a Civil 3D (or Revit) drawing and create a Dynamo session similar to the one above. (See the first article for a summary of these steps. If you’ve worked on this example before, you can reuse your script.)

2. In the Search box of Dynamo’s Library pane, type “Python” to access the Python environment. Click on Python scripting to add this node to your workspace.

Python

Click to enlarge.

3. Double click on the lower part of the Python Script node to open the Python Script editor. Notice near the bottom left of the window a drop-down list showing the two versions of Python available. For this example, we will use CPython.

Python

Click to enlarge.

4. The Python Script editor includes many boilerplate lines of code that you can ignore for now. Edit the last line to read as follows:

OUTPUT = Y2

5. Just above the 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 chart should look like this:

Python

Click to enlarge.

7. Click To 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.

Although this is a very simplified example for the sake of brevity, you can see how you can use Python to provide additional power to your programming toolkit. With Python’s more robust features like logic and flow control, along with Dynamo’s graphical environment for quickly building programs, the sky’s the limit for creating custom applications.

We will 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 email us.