Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

python.net

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");   
        }
like image 798
Naveen Kumar Avatar asked Oct 29 '25 21:10

Naveen Kumar


1 Answers

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");
}
like image 117
Naveen Kumar Avatar answered Oct 31 '25 13:10

Naveen Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!