pythoncadsiemens-nx

How to use the SIEMENS NX's "NXOpen" API in Python?


The Python code I wanted to run is:

import nxopen as nx
import os

def get_mass_properties(file_path):

    if not os.path.exists(file_path):
        raise ValueError(f"File not found: {file_path}")
    if not os.access(file_path, os.R_OK):
        raise PermissionError(f"Insufficient permissions to access file: {file_path}")

    with nx.Session() as session:
        workpart = session.parts.open(file_path)

        bodies = workpart.bodies
        if len(bodies) != 1:
            raise RuntimeError("Unsupported file format: multiple solids found")
        solid_body = bodies[0]
        
        mass = solid_body.GetMass()

        massprop = [mass]

        workpart.close()
        session.close()

    return massprop

massproperties = get_mass_properties("D:/NX Files/model1.prt")

How do I use the NXOpen Python Library which accesses the NX CAD API? I tried installing the 'NXOpen' Library with pip and when I ran my code, I got this error:

Traceback (most recent call last):
  File "d:\Coding\NXOpen\basic 2.py", line 1, in <module>
    import nxopen as nx
  File "C:\Users\johan\AppData\Local\Programs\Python\Python311\Lib\site-packages\nxopen\__init__.py", line 1, in <module>
    from . import cad
  File "C:\Users\johan\AppData\Local\Programs\Python\Python311\Lib\site-packages\nxopen\cad\__init__.py", line 1, in <module>
    from .code import *
  File "C:\Users\johan\AppData\Local\Programs\Python\Python311\Lib\site-packages\nxopen\cad\code.py", line 3, in <module>
    import NXOpen
ModuleNotFoundError: No module named 'NXOpen'

PLease help me with this!


Solution

  • NXOpen Library is already installed with NX in NX's installation directory. It seems that you ran the code from your code editor. If so, then why?

    You should run the code from inside the NX software.If you are using VSCode and need itellisense, then check out this link.

    Remember that the code should be run by NX software itself but not via the code editor.