Cadalyst CAD Management

Combining Python and .NET

Written by Andrew G. Roe | Oct 19, 2022 10:14:00 AM

In previous articles, we’ve seen how Python can add value to your programming toolbox. Specifically, we’ve seen: 1) how to get started with Python, using its easy-to-decipher syntax to accomplish simple tasks; and 2) how to use pyautocad, a specific flavor of Python designed to work within the AutoCAD environment.

As the previous articles demonstrated, Python enables you to readily develop applications with minimal training; however, it does not directly allow you to build graphical user interfaces (GUIs). If you’re developing applications to be used by a wide variety of users, you will often want to use GUIs to provide menus, buttons, and other controls that manage interaction with your program. Programmers familiar with the .NET environment appreciate the ease in building GUIs with that platform.

Fortunately, you can develop applications that leverage the benefits of both Python and .NET quite easily. This can also enable you to incorporate the work of multiple programmers who may favor one environment over the other. In this article, we’ll review how to build a GUI in .NET and access Python code to accomplish some CAD-related tasks. The example is AutoCAD-centric, but the concepts apply to other CAD environments also. To run this example, you will need Visual Studio.NET and pyautocad installed on your computer, as covered in previous articles.

Building a .NET Interface

As an object-oriented programming platform, Visual Studio.NET has gained popularity among CAD developers due to its versatility and robust feature set. It enables rapid development of GUIs and other features and allows you to work across multiple languages such as VB and C#. This example will use the VB.NET language. If you’re familiar with C#, the steps are similar. In the Visual Studio environment, build a simple GUI with the following steps.

1. Start Visual Studio and create a new project by clicking File > New > Project (click on image to enlarge).

 

2. In the New Project dialog box, select Windows Forms App, then type a name and file location in the first two fields at the bottom of the box, as shown here (click on image to enlarge).

 

3. Click OK to close the New Project dialog box.

4. In the .NET Form Designer, drag and drop a text box and two buttons onto the form. Position the controls and change the Text properties as shown (click on image to enlarge).

 

5. Double-click on the form to display the code window. Enter the following code immediately after the top line (Public Class Form1) in the code window. (Note: The Form1_Load subroutine is created automatically when you double-click on the form.)

Public Value As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Public Sub proccess_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
On Error Resume Next
If e.Data = "" Then
Else
Value = e.Data
End If
End Sub

6. Add the following code to be associated with the first button (Get Drawing Info) on the form.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myProcess As New Process()
Dim myStartInfo As New ProcessStartInfo("PATH\python.exe", "TestPython.py")
myStartInfo.UseShellExecute = False
myStartInfo.RedirectStandardOutput = True
myProcess.StartInfo = myStartInfo
myProcess.StartInfo.CreateNoWindow = True 'hide cmd window.
myProcess.Start()
Dim sOutput As String
Using myStreamReader As System.IO.StreamReader = myProcess.StandardOutput
sOutput = myStreamReader.ReadToEnd()
End Using
Console.WriteLine(sOutput)
TextBox1.Text = "The drawing name is: " & sOutput
Debug.Print(sOutput)
End Sub

7. Add the following code to be associated with the second button (Create Lines).

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim myProcess As New Process()
Dim myStartInfo As New ProcessStartInfo("PATH\python.exe", "DrawWithPython.py")
myStartInfo.UseShellExecute = False
myStartInfo.RedirectStandardOutput = True
myProcess.StartInfo = myStartInfo
myProcess.StartInfo.CreateNoWindow = True ' hide cmd window.
myProcess.Start()
Dim sOutput As String
Using myStreamReader As System.IO.StreamReader = myProcess.StandardOutput
sOutput = myStreamReader.ReadToEnd()
End Using
Console.WriteLine(sOutput)
TextBox1.Text = sOutput
Debug.Print(sOutput)
End Sub

8. For each of the code blocks associated with buttons, change the PATH to the location of Python on your computer. It’s typically found in a location similar to that shown below (click on image to enlarge). (Tip: You can right click on the folder name and copy the address as text to save some typing.)

 

Your VB.NET code should now look something like the following (click on image to enlarge):

 

9. Click Build > Build Solution to compile the project files and components. If you get any error messages, follow the prompts to address the errors.

10. Click File > Save All to save your project.

Let’s briefly review what we’ve done so far. We created a simple VB.NET form with a text box and two buttons. The first portion of code was created when we double-clicked on the form, and it includes an empty code block (Form1_Load) where we could later add code to execute when the form is loaded. We then added some code to handle the OutputDataReceived event, which will allow us to receive data from our Python code (more on that later).

We then entered code for two buttons that execute certain actions when the respective button is clicked. For the first button, the ProcessStartInfo class starts Python and executes a routine we’ll create shortly, called “TestPython.py.” The code for the second button is similar, and it executes a routine called “DrawWIthPython.py.” Both code blocks include a Print statement that prints output to the text box on our form.

 

Creating Python Code

We’re now ready to create some Python code to interact with our .NET project. You can create Python code, also referred to as scripts, in the Python interpreter or with any text editor. If you worked through the example in the previous article, you may be able to reuse some of your code from that example. For now, we’ll create Python code from scratch in a text editor.

1. In the text editor, enter the following lines of code.

from pyautocad import Autocad
acad = Autocad()
print (acad.doc.Name)

2. Save this in a file called “TestPython.py” and in the same folder as your VB.NET project, as shown below (click on image to enlarge). (In some text editors, you may need to save the file with an extension of .txt and later change it manually to an extension of .py.)

 

3. In a new file, enter the following lines of code. (Other than the last line, this was the same code used in the previous article.)

from pyautocad import Autocad, APoint
acad = Autocad()
p1 = APoint(0, 0)
p2 = APoint(5, 5)
for i in range(5):
myline = acad.model.AddLine(p1, p2)
myline.color = i
p2.y += 5
print("Creating AutoCAD objects using Python script...")

 

4. Save this in a file called “DrawWithPython.py” and in the same folder as your VB.NET project.

Let’s review the Python code. The first script imports AutoCAD into the Python environment, then simply prints the name of the AutoCAD drawing, which will be displayed in the .NET text box. The second script imports AutoCAD and the AutoCAD Point object, then creates a series of lines, changes the color of each line, and assigns a unique y value to the end point (p2) of each line. When finished, it prints a message that AutoCAD objects have been created.

 

Testing the Project

We’re now ready to test our .NET project working in tandem with Python.

1. Start AutoCAD if it’s not already running.

2. Return to VB.NET and press F5 to run the program. (You can also click Debug > Start Debugging or click the Start icon () in the menu bar.)

3. Click the Get Drawing Info button to display the drawing name (click on image to enlarge).

 

4. Click the Create Lines button to draw a series of lines.

5. Switch to AutoCAD to display the lines.

 

Onward and Upward

With this relatively simple example, you can see how .NET and Python can be used together to automate various AutoCAD tasks, leveraging the strengths of each programming environment. You could easily expand this example to do more complex tasks, and you could also package your .NET application in various ways to better serve your end users. For example, you could create a plugin to run from within the AutoCAD environment. (See previous article.)

We’ll continue to explore other programming tools in future articles. If you have specific ideas for programming topics, feel free to drop us an email.