Opracowanie standardowych skryptów automatycznych Nx z Pythonem i C#
Wprowadzenie 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 API for automation. Writing custem scripts in Python or C # allows contexers and developers to eliminate repetitive manual work, enforcee decotn standards, and integrate NX into larger conteering contexines. Whether you need to batch -export files, automate geometry y creation, or run simulations with out user intervention, masting NX scripting is a forstillie for.
This article provides an expanded, pracciale guidee to developing conserm NX automation scripts using both Python and C #. You will learn the differences between the two languages, how tu tu set up your development environment, write production- ready scripts, andd appey best practices to avoid color pitfalls. The goal is to give you a solid for building robutt automation that works stelly with your NX workflow.
Uzgodnienie to NX Automation Ecosystem
NX automation is built on the environ1; Xi1; FLT: 0 X3; XI3; NX Open API environment 1; XI1; FLT: 1 XI3; XI3;, a complessive library that exposes almost every functiality acceptable in thee NX user interface. The API is acvacable in multiple programming interfaces:
- Xi1; Xi1; FLT: 0 XI3; XI3; NX Open for Python XI1; XI1; FLT: 1 XI3; XI3; - Provides Python bindings for the NX Open API. Ideal for quick scripting, prototypine, and integration with data science libraries.
- Refl1; Refl1; FLT: 0 refl3; Efl3; Efl3; Efl3; Efl3; Efl3; Efl3.NET assemblies (C #, VB.NET) that give you accordis to the entire NX object model. Bess for complex, performance-critical applications with UI contrients.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; NX Open C + + Xi1; Xi1; FLT: 1 Xi3; Xi3; - For developers who need direct memory accords or need to link with legacy C + + code.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Journaling Xi1; Xi1; FLT: 1 Xi3; Xi3; - NX can Xidd your manual actions as a journal file (VB or C #). These journals are a geat startin g point for learning the API syntax.
All API nakreśla podobieństwo do celu modela, ale językojęzyczny-specific nuances existt. The key is to understand that NX automation is event- deportin; you typically create a eng1; eng.1; FLT: 0 constructee 3; FLT: 0 constructee 3; eng. 3; eng.1; FLT: 1 context the model; eng. 3;, eng. 1; FLT: 2 contex3;, and various builder classes to interact the model.
Choosing Between Python and C #
Decyzję tę należy podjąć na podstawie wymagań projektowych, zespołu ekspertów, a także wdrożenia ekosystemu.
Python for NX Automation
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Easy of Usie: Xi1; FLT: 1 Xi3; Xi3; Xi3; Python 's clean syntax makes it the fastest way tu write automation scripts. It is ideal for contribuers who are note full- time developers.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Rapid Prototyping: Xi1; FLT: 1 Xi3; Xi3; You can tess scripts interactively using an embedded Python console with in NX (sene NX 12).
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Data Integration: Xi1; FLT: 1 Xi3; Xi3; Xi3; Xithon 's vast ecosystem (NumPy, Pandas, Matplalib) allows you tu tu combination with data analysis and visualization.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Performance: Xi1; Xi1; FLT: 1 Xi3; Xi3; Xithon is interpreted; for very large assemblies or crutt loops, it may by slower than C #. However, for mott scripting tasks, the overhead is negligible.
- Xi1; Xi1; FLT: 0 X3; Xi3; Deployment: Xi1; Xi1; FLT: 1 XI3; Xi3; Python scripts are e plain text files. They can be run inside NX via the Xion1; XI1; FLT: 2 XI3; XI3; XI3; XIe → Execute → NX Open Xion1; XINX; FLT: 3 X3; X3; menu or by using the XI1; XIN: 1; XIN: 3 X3; X3; XD; Command in the.
C # for NX Automation
- W przypadku gdy w ramach projektu nie ma zastosowania art. 3 ust. 1 lit. a) ppkt (ii), w przypadku gdy projekt jest realizowany w sposób niezgodny z prawem, należy podać numer identyfikacyjny, w którym producent może przedstawić informacje dotyczące jego działalności.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Strongly Typed: Xi1; Xi1; FLT: 1 Xi3; Xi3; C # catches many errors at compile time, making it easyr to o maintain large codebases.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Integration with Other Siemens Tools: Xi1; Xi1; FLT: 1 Xi3; Xi3; Many Siemens PLM products (like Teamcenter) provide nativa .NET APIs that pair well with C # automation.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Performance: Xi1; Xi1; FLT: 1 Xi3; Xi3; Compiled code runs faster than interpreted Python, especially for operations that iterate over exiterands of faces or edges.
- Xi1; Xi1; FLT: 0 XI3; XI3; Deployment: XI1; XI1; FLT: 1 XI3; XI3; C # scripts mutt be compiled into DLL or executables. They can be loaded as NX add- ons via via exe.1; XI1; FLT: 2 XI3; XI3; XI3; File → Commities → User Tools exe1; XI1; FLT: 3 XI3; OR by claming the DLL in the startup folder.
In practice, many teams use both: Python for ad- hoc tasks andd proof-of- concepts, and C # for mission-critical tools that need a polished interface andd high performance.
Setting Up Python for NX Automation
Warunki wstępne
- Siemens NX (wersja 12 or later is recommended; Python support was enhanced in NX 1926 Series).
- Python 3.x installalod on thee same machine (NX does not ship it own Python; you need to install a compatible version).
- Thee Xion1; Xion1; FLT: 4 Xion3; Xion3; package. This is often included with thee NX installation but may require setting environment variables.
Konfiguracja środowiska
Before writing your first script, ensure NX can find your Python interpreter. In Windows, add the Python installation folder to thee direct 1; insure NX can find your Python interpretes. Then, inside NX, check that direc1; indicable 1; FLT: 0 X3; If YOU GET AN Quet; File → Execute → NX Open → Python X1; FLT: 1 X3; EB; EF 3; works with out errors. If YOU GET AN Quet; Unable TH TH TH; Message, verify thath; VE 1; FLT: 6; 3AE; dicabble 3OT: 0; dicabble; dicable dicable dibult dicult dicult dicut.
You-First Python Script
Launch NX, create a new part file (np., Xi1; Xi1; FLT: 7 contribution 3; Xi3;), then open thee NX Python Editor (or use an external IDE like VS Code). Enter thee following script and run it frem wisin NX via indivin NX 1; FLT: 0 extribute 3; File → Execute → NX Open → Browsie previo1; FLT: 1 extribute 3; 3;
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 destruy the builder.
Key Python Modules to Know
- Xiv1; Xiv1; FLT: 9 Xiv3; Xiv3; - The main namespace for all NX objects.
- - User Functionion calls (older API, still used for some low- level tasks).
- - Helpers for unit conversions, math, etc.
Setting Up C # for NX Automation
Warunki wstępne
- Siemens NX Installad.
- Visual Studio (any edition that supports. NET Framework 4.7.2 or later).
- NX Open .NET assemblies. They are e typically located in present 1; FLT: 12 presents 3; British 3; (adjuss version number).
Projekt Studio Creating a Visual
- Stworzenie nowego projektu C # Class Library (.NET Framework).
- Dodać referencje do tego wymogu NX assemblies: XXX1; XXX1; FLT: 0 XXX3; XXX1; XXX1; FLT: 1 XXX3; XXX3; XXX3; XXX1; FLT: 13 XXX3; XXX3;
- (optional, for UF calls)
- Xiv1; Xiv1; FLT: 15 Xiv3; Xiv3;
- Set thee 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 tect this DLL, compile it andthen inside NX go to vir1; direction 1; FLT: 0 vir3; File → Execute → NX Open → Browsie vir1; direction 1; FLT: 1 vir3; direction 3; and select the DLL. NX will execute the vir1; direct 1; FLT: 17 virrei3; metod automatically if you mark it as the entry point (you can also usie the vine 1; direcorse 1; FLT: 18 vir3; direcorse 3o; tionch a crt).
Debugging C # Scripts
Attach Visual Studio to NX process (vide1; vide1; FLT: 0 + 3; Xe3; Debug → Attach to Process Bride1; Xe1; FLT: 1 + 3; XeD; FLT: 1; FLT: 19 + 3; XE). Set breakpoints in your C # code and run the script frem inside NX. This gives you full variable inspection and step - distrigh debugging, ain vitage over Python 's simpler pred 1; XE 10; FLT: 20; 3BaxD 3statetes.
Core Automation Patterns
Regardless of language, every NX automation script follows a similar lifecycle:
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Get the currit session Xi1; Xi1; FLT: 1 Xi3; Xi3; - Xi1; FLT: 21 Xi3; Xi3; in both languages.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Get the working part Xi1; Xi1; FLT: 1 Xi3; Xi3; - Xi1; FLT: 22 Xi3; Xi3; (or Xi1; Xi1; FLT: 23 Xi3; Xi3; for the visible part).
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Create a builder Xi1; Xi1; FLT: 1 Xi3; Xi3; - Use methods like Xi1; Xi1; FLT: 24 Xi3; Xi3;
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Set parameters Xi1; Xi1; FLT: 1 Xi3; Xi3; - Usie the builder 's methods (np., Xi1; Xi1; FLT: 25 Xi3; Xi3;, Xi1; FLT: 26 Xi3; Xion3;).
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Commit the builder Xi1; Xi1; FLT: 1 Xi3; Xi3; - This creates the actual NX object andd returns it.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Destroy the builder Xi1; Xi1; FLT: 1 Xi3; Xi3; - Releases memory.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Update the parte Xi1; Xi1; FLT: 1 Xi3; Xi3; - Zwykłe przypadki automatyki, ale for some operations you need to call Xi1; Xi1; FLT: 27 Xi3; Xion3;
For operations that involve selection (np., user picks a face), you use the present 1; indi1; FLT: 28 contribution 3; indisation 3; class. You can create a selection dialog inside the script or let the user select objects previohand by using interactive selection methods.
Skrypt: Batch Export Parts to STEP
Let 's build a real-term utility: export all open part files to STEP format. This is a form requirement for collaboration with tell 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 thrimagh all loaded parts (inding the display part) and exports each to STEP using the indiv1; indiv1; FLT: 30 indiv3; endiv3;.
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 thee necessary export permissions and that NX can write to to the output folder. Error handling (tr- catch) should be added in production code.
Begt Practices for Script Development andDeployment
Code Structured andMaintenability
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Modularization: Xi1; Xi1; FLT: 1 Xi3; Xi3; FLT: XiUR script into functions or classes. In C #, use separate files for different Xiure groups.
- Reg.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; Version Contral: Xi1; Xi1; FLT: 1 Xi3; Xi3; FLT: Usie Git to to track changes. NX scripts evolve as your part designs change.
Error Handling and Logging
- Wrap API wzywa in try- except (Python) or try- catch (C #) blocks. Check prefectu1; Xi1; FLT: 34 prefectu3; Xi3; for specific NX errors.
- Usie NX 's Bead1; Xi1; FLT: 35 Xi3; Xi3; for real- time fearback. For logs, write to a text file using Xi1; Xi1; FLT: 36 Xion3; Xion3; (C #) or standard Python logging.
- Always destruy builders in a behin1; Behin1; FLT: 37 behind 3; Behin3; block or using behind; Behin1; FLT: 38 behind 3; Behind 3; behind; statement (C #) to avoid memory less.
Rozważanie wydajności
- Minimize the number of API calls inside loops. For example, if you need to accords a part 's concluure collection many times, story it in a variable.
- For large assemblies, use presents 1; EI1; FLT: 39 presents 3; EI3; flags to avoid fuly loading contents you don 't need.
- Turn off screen updates during batth operations. In C #, use present 1; Ig1; FLT: 40 presents 3; Ig3; and re- enable after.
- In Python, you can use present 1; EI1; FLT: 41 presentation 3; IU3;
Testing
- Teszt scripts in behind 1; Behind 1; FLT: 0 behind 3; Behind 3; Isolated NX session behind 1; Behind 1 behind 3; Behind; (start NX with a new empty part).
- Create tect parts with known geometrgy to validate outputs.
- For C # DLLs, write unit tests using a mosking framework (like Moq) to simulate NX objects - though testing against a real NX instance is more reliable.
Wdrożenie
- Pisemne skrypty: Distribute as present 1; EDI1; FLT: 42 presents 3; EDI3; files. Ensure all users have compatible Python and NX versions.
- C # scripts: Provide a compiled DLL along with a manifest file (presendi1; FLT: 43 presenti3; presenti3;) that registers the add- in. Alternatively, place thee DLL in thee presenti1; presenti1; FLT: 44 presenti3; presenti3; folder under NX installation to auto- load.
Rozwiązywanie problemów Common Emites
API Version Mismatches
NX Open API is version- specific. A script written for NX 1926 may nott work with NX 1980 without out modifications. Always check the e.i.1.; XI.; FLT: 45 contribution 3; XI.3; at runtime and adjust methods calls accordly. Refer tone thee e.1; FLT: 0 contribution3; FLT: 0 contribution3; Siemens NX API documentation beh1; XI.FLT: 1; FLT: 1 contribuend 3; for thee correcort version.
Python Import Errors
If you see presendi1; Ig1; FLT: 46 extendi3; Ig3;, ensure that presendi1; Ig1; FLT: 47 exendiditi3; Is in your Python path. The file is usually in presendi1; Ig1; FLT: 48 extendisation 3; Ig3;. Add this path tu your presendi1; Ig1; FLT: 49 extred; Igrent variable.
Komitet Builder Not
If your script does nothing, verify that you called indic1; indic1; FLT: 50 contribution 3; indic3; and not just indic1; indic1; FLT: 51 contribution 3; indic3. also, check that the builder parameters are valid (np., negative lengths cause exceptions).
Dopuszczalne i File Acces
Batch export scripts often fail because NX does none have write accessis to to thee output folder. Run NX as administrator or choose a folder in your user profile. Usie english 1; Defic.1; FLT: 52 contributions 3; metricreas3; to resolve relativa paths.
Konkluzja
Developing customm automation scripts with Python and C # unlocks the full potential of Siemens NX, enabling you tu streaminale repetititivy tasks, expercy standards, and integrate with larger PLM systems. Python excels at rapid development and datat are relize and mainable across # offers robutt performance andd advanced UI capabilities. By conceptiing thee NX Open API, setting up yor environt correcorrectly, and approvident beses for error handling and perfore, yon built, youn cutt scripte, en cade thet arable are are are are mainte and maintaintaintanable NX version
Start small: journal a manual operation, convert it to a Python script, then gradually add complexity. As you gain confidence, exploore the deeper capabilities of the API - conserm cocure creation, simulation automation, and even linking NX with external databases. The contribuild 1; FLT: 0 contribuild for finding examps and asking. With. Wiedza frogem flé; FLT: 1 contri3APHE-3AHEspeln excellent resource for finding examps and asking. With the fabknowhe flhem föl, ype föl, yoare now equipd ned ned nen nen nen tour ne@@