Changing the code of a GHPython Script Component with a RhinoCommonPlugin

I’m creating a RhinoCommon Plugin that let’s me create GHPython Script Components in GH by executing a command in Rhino.
I have installed Grasshopper and RhinoCommon with NuGet in my project and I’m able to successfully create GHPython Script Components like this:

var pythonComponentGuid = new Guid("410755b1-224a-4c1e-a407-bf32fb45ea7e");
var pythonComponent = Instances.ComponentServer.EmitObject(pythonComponentGuid) as IGH_Component;
ghDoc.AddObject(pythonComponent, false);

I want to set the python code of that component within my plugin but I cannot figure out how to do it.

I tried casting it to GhPython.Component.ZuiPythonComponent but I don’t know how to import GhPython into my project.


I figured it out. This is the solution:

var scriptField = pythonComponent.GetType().GetProperty("Code", BindingFlags.Public | BindingFlags.Instance);
if (scriptField != null)
    scriptField.SetValue(pythonComponent, "x = 42");
1 Like

Hi @Robin_Wiethuechter ,
Very interesting. Thank you for sharing the solution!
How did you generate the component guid ("410755b1-224a-4c1e-a407-bf32fb45ea7e")?

1 Like

Hi @djordje

I just added a GHPython component in GH with the UI and ran a command that lists all components and their GUID.

// Get the current active Grasshopper document.
GH_Document ghDoc = Grasshopper.Instances.ActiveCanvas.Document;

// Check if a document is open.
if (ghDoc == null)
    Console.WriteLine("No open document found");
    return Result.Failure;

// Get all the components in the document.
IList<IGH_DocumentObject> components = ghDoc.Objects;

// Print the name of each component.
foreach (var component in components)
    Console.WriteLine("Component name: " + component.Name);
    Console.WriteLine("Component type: " + component.GetType().ToString());
    Console.WriteLine("Component GUID: " + component.ComponentGuid);
1 Like

Hi @Robin_Wiethuechter ,
Thank you very much for this answer as well.
So you basically manually create (drag) a couple of new (and empty) GHPython components, just to obtain their Guids? And then you use those Guids (for the code from the your first reply in this topic) to automate “filling” these empty GHPython components with code?

You’re very welcome @djordje
Kind of. Printing the components in the file is only necessary to find out the GUID once. Each GHPython Component has that exact GUID, it does not change if you modify the component and does not correspond to a specific GH file. It also doesn’t encode any information (like attributes or properties) except for what kind of component it is.

1 Like

Thank you @Robin_Wiethuechter ,
Do you create .ghuser or .ghpy files from those GHPython components?
Just curious.