control-systems-and-automation
Developing Custom Nx Automation Scripts with Python and C#
Table of Contents
Introduction to Custom NX Automation Scripts
Siemens NX is a powerful CAD/CAM/CAE platform that goes beyond manual modeling by exposing a rich set of APIs for automation. Writing custom scripts in Python or C# allows engineers and developers to eliminate repetitive manual work, enforce design standards, and integrate NX into larger engineering pipelines. Whether you need to batch-export files, automate geometry creation, or run simulations without user intervention, mastering NX scripting is a force multiplier for any design team.
This article provides an expanded, practical guide to developing custom NX automation scripts using both Python and C#. You will learn the differences between the two languages, how to set up your development environment, write production-ready scripts, and apply best practices to avoid common pitfalls. The goal is to give you a solid foundation for building robust automation that works seamlessly with your NX workflow.
Understanding the NX Automation Ecosystem
NX automation is built on the NX Open API, a comprehensive library that exposes almost every functionality available in the NX user interface. The API is available in multiple programming interfaces:
- NX Open for Python – Provides Python bindings for the NX Open API. Ideal for quick scripting, prototyping, and integration with data science libraries.
- NX Open for .NET – Full-featured .NET assemblies (C#, VB.NET) that give you access to the entire NX object model. Best for complex, performance-critical applications with UI components.
- NX Open C++ – For developers who need direct memory access or need to link with legacy C++ code.
- Journaling – NX can record your manual actions as a journal file (VB or C#). These journals are a great starting point for learning the API syntax.
All APIs share a similar object model, but language-specific nuances exist. The key is to understand that NX automation is event-driven; you typically create a Session object, then use its Parts, WorkPart, and various builder classes to interact with the model.
Choosing Between Python and C#
The decision between Python and C# for NX automation depends on your project requirements, team expertise, and deployment environment. Here’s a detailed comparison:
Python for NX Automation
- Ease of Use: Python’s clean syntax makes it the fastest way to write automation scripts. It is ideal for engineers who are not full-time developers.
- Rapid Prototyping: You can test scripts interactively using an embedded Python console within NX (since NX 12).
- Data Integration: Python’s vast ecosystem (NumPy, Pandas, Matplotlib) allows you to combine NX automation with data analysis and visualization.
- Performance: Python is interpreted; for very large assemblies or tight loops, it may be slower than C#. However, for most scripting tasks, the overhead is negligible.
- Deployment: Python scripts are plain text files. They can be run inside NX via the File → Execute → NX Open menu or by using the
nxopen()command in the NX command line.
C# for NX Automation
- Full Access to .NET: C# gives you the entire .NET framework, including Windows Forms or WPF for custom UI dialogs, background threads, and advanced debugging in Visual Studio.
- Strongly Typed: C# catches many errors at compile time, making it easier to maintain large codebases.
- Integration with Other Siemens Tools: Many Siemens PLM products (like Teamcenter) provide native .NET APIs that pair well with C# automation.
- Performance: Compiled code runs faster than interpreted Python, especially for operations that iterate over thousands of faces or edges.
- Deployment: C# scripts must be compiled into DLLs or executables. They can be loaded as NX add-ons via File → Utilities → User Tools or by placing the DLL in the startup folder.
In practice, many teams use both: Python for ad-hoc tasks and proof-of-concepts, and C# for mission-critical tools that need a polished interface and high performance.
Setting Up Python for NX Automation
Prerequisites
- Siemens NX (version 12 or later is recommended; Python support was enhanced in NX 1926 Series).
- Python 3.x installed on the same machine (NX does not ship its own Python; you need to install a compatible version).
- The
NXOpenPythonpackage. This is often included with the NX installation but may require setting environment variables.
Environment Configuration
Before writing your first script, ensure NX can find your Python interpreter. In Windows, add the Python installation folder to the PATH environment variable. Then, inside NX, check that File → Execute → NX Open → Python works without errors. If you get an “Unable to load Python” message, verify that the PYTHONHOME variable points to your Python root directory.
Your First Python Script
Launch NX, create a new part file (e.g., test.prt), then open the NX Python editor (or use an external IDE like VS Code). Enter the following script and run it from within NX via File → Execute → NX Open → Browse.
import NXOpen
def main():
session = NXOpen.Session.GetSession()
work_part = session.Parts.Work
# Create a block
body_feature = work_part.Features.CreateBlockBuilder(NXOpen.Features.BlockBuilder.Null)
body_feature.BlockBuilder.SetOrigin(NXOpen.Point3d(0, 0, 0))
body_feature.BlockBuilder.SetLengths(NXOpen.Point3d(100, 50, 30))
nx_object = body_feature.Commit()
body_feature.Destroy()
print("Block created successfully!")
if __name__ == '__main__':
main()
When executed, this script creates a 100×50×30 mm block at the origin. The pattern is the same for almost any geometry creation: get a builder, set parameters, commit, and destroy the builder.
Key Python Modules to Know
NXOpen– The main namespace for all NX objects.NXOpen.UF– User Function calls (older API, still used for some low-level tasks).NXOpen.Utilities– Helpers for unit conversions, math, etc.
Setting Up C# for NX Automation
Prerequisites
- Siemens NX installed.
- Visual Studio (any edition that supports .NET Framework 4.7.2 or later).
- NX Open .NET assemblies. They are typically located in
C:\Program Files\Siemens\NX1926\NXBIN\managed(adjust version number).
Creating a Visual Studio Project
- Create a new C# Class Library (.NET Framework) project.
- Add references to the required NX assemblies:
NXOpen.dllNXOpen.UF.dll(optional, for UF calls)NXOpen.Utilities.dll
- Set the platform target to x64 (NX is 64-bit only).
- Build the project to create a DLL.
Your First C# Script
This example does the same as the Python one: create a block.
using NXOpen;
public class CreateBlockExample
{
public static void Main()
{
Session session = Session.GetSession();
Part workPart = session.Parts.Work;
Features.BlockBuilder blockBuilder = workPart.Features.CreateBlockBuilder(null);
blockBuilder.SetOrigin(new Point3d(0, 0, 0));
blockBuilder.SetLengths(new Point3d(100, 50, 30));
NXObject block = blockBuilder.Commit();
blockBuilder.Destroy();
session.ListingWindow.WriteLine("Block created.");
}
}
To test this DLL, compile it and then inside NX go to File → Execute → NX Open → Browse and select the DLL. NX will execute the Main() method automatically if you mark it as the entry point (you can also use the NXOpen.UI to launch a custom command).
Debugging C# Scripts
Attach Visual Studio to the NX process (Debug → Attach to Process → select nx.exe). Set breakpoints in your C# code and run the script from inside NX. This gives you full variable inspection and step-through debugging, an advantage over Python’s simpler print() statements.
Core Automation Patterns
Regardless of language, every NX automation script follows a similar lifecycle:
- Get the current session –
Session.GetSession()in both languages. - Get the working part –
session.Parts.Work(orsession.Parts.Displayfor the visible part). - Create a builder – Use methods like
workPart.Features.CreateBlockBuilder(). - Set parameters – Use the builder’s methods (e.g.,
SetOrigin,SetLengths). - Commit the builder – This creates the actual NX object and returns it.
- Destroy the builder – Releases memory.
- Update the part – Usually happens automatically, but for some operations you need to call
workPart.ModelingViews.WorkView.Update().
For operations that involve selection (e.g., user picks a face), you use the SelectionManager class. You can create a selection dialog inside the script or let the user select objects beforehand by using interactive selection methods.
Writing a Practical Script: Batch Export Parts to STEP
Let’s build a real-world utility: export all open part files to STEP format. This is a common requirement for collaboration with other CAD systems. We’ll provide both Python and C# versions.
Python Batch Export
import NXOpen
import os
def export_part_to_step(part, output_folder):
part_fsa = part.FullPath # full file path
if not part_fsa:
print(f"Part {part.Name} has no file path, skipping.")
return
step_filename = os.path.join(output_folder, part.Name.replace(".prt", ".stp"))
# Create step export builder
step_builder = part.StepExportBuilder()
step_builder.FileName = step_filename
step_builder.Commit()
step_builder.Destroy()
print(f"Exported {part.Name} to {step_filename}")
def main():
session = NXOpen.Session.GetSession()
parts = session.Parts
output = r"C:\temp\step_exports"
if not os.path.exists(output):
os.makedirs(output)
for part in parts:
# Skip display part and work part duplicates
if part == parts.Display or part == parts.Work:
continue
export_part_to_step(part, output)
if __name__ == '__main__':
main()
This script iterates through all loaded parts (excluding the display part) and exports each to STEP using the StepExportBuilder.
C# Batch Export
using NXOpen; using System.IO; public class BatchStepExport { public static void Main() { Session session = Session.GetSession(); PartCollection parts = session.Parts; string outputFolder = @"C:\temp\step_exports"; Directory.CreateDirectory(outputFolder); foreach (Part part in parts) { if (part == parts.Display || part == parts.Work) continue; string partPath = part.FullPath; if (string.IsNullOrEmpty(partPath)) continue; string stepFile = Path.Combine(outputFolder, Path.GetFileNameWithoutExtension(partPath) + ".stp"); StepExportBuilder builder = part.StepExportBuilder(); builder.FileName = stepFile; builder.Commit(); builder.Destroy(); session.ListingWindow.WriteLine($"Exported {part.Name} -> {stepFile}"); } } }Both scripts assume you have the necessary export permissions and that NX can write to the output folder. Error handling (try-catch) should be added in production code.
Best Practices for Script Development and Deployment
Code Structure and Maintainability
- Modularization: Break your script into functions or classes. In C#, use separate files for different feature groups.
- Consistent Naming: Follow the NX API naming conventions. Use
PascalCasein C# andsnake_casein Python for local variables. - Version Control: Use Git to track changes. NX scripts evolve as your part designs change.
Error Handling and Logging
- Wrap API calls in try-except (Python) or try-catch (C#) blocks. Check
NXExceptionfor specific NX errors. - Use NX’s
ListingWindowfor real-time feedback. For logs, write to a text file usingSystem.IO.StreamWriter(C#) or standard Python logging. - Always destroy builders in a
finallyblock or usingusingstatement (C#) to avoid memory leaks.
Performance Considerations
- Minimize the number of API calls inside loops. For example, if you need to access a part’s feature collection many times, store it in a variable.
- For large assemblies, use
Part.LoadStatusflags to avoid fully loading components you don’t need. - Turn off screen updates during batch operations. In C#, use
session.UpdateManager.SetEnabled(false)and re-enable after. - In Python, you can use
session.UpdateManager.SetUpdateMode(UpdateManager.UpdateMode.NoUpdate).
Testing
- Test scripts in Isolated NX session (start NX with a new empty part).
- Create test parts with known geometry to validate outputs.
- For C# DLLs, write unit tests using a mocking framework (like Moq) to simulate NX objects – though testing against a real NX instance is more reliable.
Deployment
- Python scripts: Distribute as
.pyfiles. Ensure all users have compatible Python and NX versions. - C# scripts: Provide a compiled DLL along with a manifest file (
.manifest) that registers the add-in. Alternatively, place the DLL in thestartupfolder under NX installation to auto-load.
Troubleshooting Common Issues
API Version Mismatches
NX Open API is version-specific. A script written for NX 1926 may not work with NX 1980 without modifications. Always check the Session.Version at runtime and adjust method calls accordingly. Refer to the Siemens NX API documentation for the correct version.
Python Import Errors
If you see ModuleNotFoundError: No module named 'NXOpen', ensure that NXOpen.py is in your Python path. The file is usually in <NXInstall>\UGOPEN\Python. Add this path to your PYTHONPATH environment variable.
Builder Not Committed
If your script does nothing, verify that you called Commit() and not just Build(). Also, check that the builder parameters are valid (e.g., negative lengths cause exceptions).
Permissions and File Access
Batch export scripts often fail because NX does not have write access to the output folder. Run NX as administrator or choose a folder in your user profile. Use System.IO.Path.GetFullPath() to resolve relative paths.
Conclusion
Developing custom automation scripts with Python and C# unlocks the full potential of Siemens NX, enabling you to streamline repetitive tasks, enforce standards, and integrate with larger PLM systems. Python excels at rapid development and data-rich processes, while C# offers robust performance and advanced UI capabilities. By understanding the NX Open API, setting up your environment correctly, and following best practices for error handling and performance, you can build scripts that are reliable and maintainable across NX versions.
Start small: journal a manual operation, convert it to a Python script, then gradually add complexity. As you gain confidence, explore the deeper capabilities of the API—custom feature creation, simulation automation, and even linking NX with external databases. The Siemens PLM Community is an excellent resource for finding examples and asking questions. With the knowledge from this article, you are now equipped to build your own NX automation toolkit.