Executing Python 3 Script in C#

I’ve been successfully using Rhino.Runtime.PythonScript to run IronPython scripts directly in C#:

private void RunScript(ref object a)
{
    var script = Rhino.Runtime.PythonScript.Create();
    script.ExecuteScript("import sys\na=sys.version");
    a = script.GetVariable("a");
}

Now, I’m attempting to execute Python 3 code directly from C# using the RhinoCodePlatform.Rhino3D.Languages.Python3Script class:

private void RunScript(ref object a)
{
    var script = RhinoCodePlatform.Rhino3D.Languages.Python3Script.Create();
    script.ExecuteScript("import sys\na=sys.version");
    a = script.GetVariable("a");
}


PythonInCSharp.gh (9.4 KB)

It seems that despite using Python3Script, it still executes Python 2 code. @eirannejad, could you please advise if there’s a method to execute Python 3 code directly from C# in Rhino? Any help or alternative methods would be greatly appreciated.

1 Like

@Mahdiyar

  • :warning: RhinoCodePlatform.Rhino3D.Languages.Python3Script.Create(); is a static method on the base PythonScript class that ALWAYS creates an IronPython script using the legacy IronPython plugin.
  • :warning: Python3Script is undocumented and unsupported API at this point. It does not even work in Rhino 8 as it was made to use internally in Rhino 9.
  • :warning: Any dll that is named RhinoCodePlatform.* is undocumented API

RhinoCode API

The core api for running scripts in Rhino >=8 is called RhinoCode and is under Rhino.Runtime.Code and is still being matured under Rhino 8 and is undocumented.

However, to be a bit more future-proof use this api:

using Rhino.Runtime.Code;
using Rhino.Runtime.Code.Execution;

// context holds execution configs, and input/output parameters
var ctx = new RunContext {
  AutoApplyParams = true,
  Inputs = {
    ["x"] = 21,
    ["y"] = 21,
  },
  Outputs = {
    ["a"] = 0
  }
};

// run script with created context
RhinoCode.RunScript("#! python 3\na = x + y", ctx);

// inspect context for return values
a = ctx.Outputs.Get<int>("a");

This api is language agnostic. Note that language specifier is added to the script itself:

NestedScripts.gh (9.4 KB)

It is worth noting that this API is fairly low level and is still maturing but all the new scripting functionality is built on top of this and does not have any legacy dependencies.

3 Likes

Nice! Thank you for the clear explanation, @eirannejad. I appreciate your guidance on using Rhino.Runtime.Code.

1 Like