Naveen Kumar
Naveen Kumar

Reputation: 145

Python.Net - How to run python script from file(.Py)

How to run .py files and call function by using python.Net library. i have tried below code but it is not running.

    using (Py.GIL()){
      var fromFile = PythonEngine.Compile(null, @"C:\PycharmProjects\pythonenet\main.py", RunFlagType.File);
      fromFile.InvokeMethod("replace");//
    }

main.py file:

import re
def replace():
 print(re.sub(r"\s","*","Python is a programming langauge"))

When i try to run from string it is working.

       using (Py.GIL()){
          string co = @"def someMethod():
                print('This is from static script')";
          var fromString = PythonEngine.ModuleFromString("someName", co);
          fromString.InvokeMethod("someMethod");   
        }

Upvotes: 4

Views: 5010

Answers (1)

Naveen Kumar
Naveen Kumar

Reputation: 145

Finally i ended up with the following solution.

using (Py.GIL()){
    dynamic os = Py.Import("os");
    dynamic sys = Py.Import("sys");
    sys.path.append(os.path.dirname(os.path.expanduser(filePath)));
    var fromFile = Py.Import(Path.GetFileNameWithoutExtension(filePath));
    fromFile.InvokeMethod("replace");
}

Upvotes: 5

Related Questions