Can Python code know if it's running in Rhino.Inside / Grasshopper

Hi folks,

let’s see if I can explain myself…

I have a Python package that I have been using with Dynamo in Revit. It has several modules and it includes all necessary imports from the Revit API.
Recently I ported this package to Grasshopper to be used in Rhino.Inside and I found that I could run it with no modifications provided I had run it once already in Dynamo in the same session.
However, If I try to run it in Grasshopper WITHOUT opening Dynamo first it will fail with an ImportError because I’m using imports that belong to Dynamo and not to Rhino / Grasshopper.

For example, the active document variable has to be called differently depending on the scripts host:

In Dynamo: doc = DocumentManager.Instance.CurrentDBDocument
In Grasshopper: doc = Revit.ActiveDBDocument

I’m guessing that when I load the modules in Dynamo they are cached in IronPython and when the Rhino.Inside session starts thay are all there and I don’t get any errors.
This is black magic to me at this stage.

So, to sum it all up: what would be the best way for my script to check it is running in Dynamo or Grass and then do the imports accordingly?

Best to all

ps.- when dealing with RevitPythonShell or Dynamo I usually use a try / except block like so:

try:
    # RPS
    uidoc = __revit__.ActiveUIDocument
    doc = __revit__.ActiveUIDocument.Document
    app = __revit__.Application
    uiapp = __revit__

except NameError as ex:
    doc = DocumentManager.Instance.CurrentDBDocument
    uiapp = DocumentManager.Instance.CurrentUIApplication
    app = uiapp.Application
1 Like

Welcome @Iván_Pajares to the RIR community :smiley:

When Dynamo is loaded, the DLL libraries that bring the Dynamo functionality are also loaded in your application. Since IronPython is running in the same application, it can see the loaded libraries and can import them. But if Dynamo is not loaded, IronPython has no idea where and how to load those libraries.

An easy way to check whether you are running in GH is to import rhinoscriptsyntax library that is only available in GH:

IN_GRASSHOPPER = False

try:
    import rhinoscriptsyntax
    # we are in Grasshopper on this line since the import
    # above did not throw an exception
    # we can set a global variable to true here so this can be used
    # in the rest of our script very easly
    IN_GRASSHOPPER = True
except:
    # we are not in Grasshopper on this line
    # maybe try to import Dynamo?
1 Like