Calling(running) python script from c# plugin

Hi all,

I’m trying to run a python script from my coworker in a plugin i’m writing in c#. (Sorry Dale i don’t know how to edit the text like you did last time).

ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.ExecuteFile("{myPath}/"); engine.ExecuteFile(“{myPath}/”);
dynamic testFunction = scope.GetVariable(“main()”);

The plugin is opening the file and then tries to import all libraries and necessary files. These are written in python.

import prmd_convert_cfg
import stl_export
import ps2d
import pmc
import Rhino
import Eto.Drawing as drawing
import Eto.Forms as forms
import datetime
import os

I’m succeeding to this for the first 4. But i cant figure out how to dis for the Rhino namespace and probably also for ETO drawing, Forms, datetime and os.

can anyone help me out with this?
I also tried running the runscript command through the commandline but then i’m encoutering other problems. Also this doesnt seem like a flexible way to do this.

Thanks in advance
Gr Reinder

Hi @r.weenink,

Maybe something like this would work for you?

public class TestRunPythonScriptCommand : Rhino.Commands.Command
  public override string EnglishName => "TestRunPythonScript";

  protected override Result RunCommand(RhinoDoc doc, RunMode mode)
    var folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
    var path = System.IO.Path.Combine(folder, "");
    if (System.IO.File.Exists(path))
      var script = string.Format("_-RunPythonScript \"{0}\"", path);
      RhinoApp.RunScript(script, false);
    return Result.Success;

– Dale

I encountered a similar challenge recently and would also appreciate some guidance.

How can I output a Python class from a Grasshopper C# component? I’m working with the Ladybug tools, which require specific Python classes as input. For many reasons I’d prefer to write my components in C# while still maintaining compatibility with Ladybug.

What would you recommend?

Hi Dale,

Thank you. I’ve used your script but python isnt running. Below the string which is being generated.

“_-RunPythonScript "C:\Users\reinder\OneDrive - PLT Products\ModellingPlugIn\bin\Debug\net48/prmdToolpathGenerator\"”.

The path Exists returns true btw.
I cant see what i’m doing wrong. Do you have any suggestions?

kind reagrds Reinder

Hi Dale,

Finally i found my error. I failed to add the first line of your code.

kind regards Reinder