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:

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

C # for NX Automation

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

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

Setting Up C # for NX Automation

Warunki wstępne

Projekt Studio Creating a Visual

  1. Stworzenie nowego projektu C # Class Library (.NET Framework).
  2. Dodać referencje do tego wymogu NX assemblies: XXX1; XXX1; FLT: 0 XXX3; XXX1; XXX1; FLT: 1 XXX3; XXX3; XXX3; XXX1; FLT: 13 XXX3; XXX3;
  3. (optional, for UF calls)
  4. Xiv1; Xiv1; FLT: 15 Xiv3; Xiv3;
  5. Set thee platform target to x64 (NX is 64- bit only).
  6. 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:

  1. Xi1; Xi1; FLT: 0 Xi3; Xi3; Get the currit session Xi1; Xi1; FLT: 1 Xi3; Xi3; - Xi1; FLT: 21 Xi3; Xi3; in both languages.
  2. 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).
  3. Xi1; Xi1; FLT: 0 Xi3; Xi3; Create a builder Xi1; Xi1; FLT: 1 Xi3; Xi3; - Use methods like Xi1; Xi1; FLT: 24 Xi3; Xi3;
  4. 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;).
  5. Xi1; Xi1; FLT: 0 Xi3; Xi3; Commit the builder Xi1; Xi1; FLT: 1 Xi3; Xi3; - This creates the actual NX object andd returns it.
  6. Xi1; Xi1; FLT: 0 Xi3; Xi3; Destroy the builder Xi1; Xi1; FLT: 1 Xi3; Xi3; - Releases memory.
  7. 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@@