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");
}
CodePudding user response:
The purpose of Python.NET (pythonnet) is to enable fast scripting for .NET developers. Python.NET is used to script .NET components (like C#, VB.NET, F3). If your goal is to make one Python program run another Python program, you can use the features provided by Python:
# service.py
import main
def something():
print('service: something()')
if __name__ == '__main__':
something()
main.something()
# main.py
import subprocess
def something():
print('main: something()')
if __name__ == '__main__':
something()
subprocess.call("service.py", shell=True)
The output in the first group below is produced by running the main.py
program, and the output in the second group is produced by running the service.py
program.
# Running the "main.py" file produces the following output:
main: something()
service: something()
main: something()
# Running the "service.py" file produces the following output:
service: something()
main: something()
Note that two different solutions are used above:
- Added
import main
command line to includemain.py
file inservice.py
file. - The
subprocess
module was used to run theservice.py
file from themain.py
file.
CodePudding user response:
Finally i ended up with the following solution.
using (Py.GIL()){
string file_path = @"C:\PycharmProjects\pythonnet\main.py";
string final_path = null;
string module_name = null;
if (file_path.EndsWith(".py"))
{
int delim = file_path.LastIndexOf(@"\");
final_path = file_path.Substring(0,delim > 0 ? delim : 0); //C:\PycharmProjects\pythonnet
int module_length = (file_path.Length - delim) - 4;
if (module_length > 0)
module_name = file_path.Substring(delim 1, module_length);//main
}
if (final_path != null && module_name != null)
{
dynamic ps = Py.Import("sys");
ps.path.append(final_path);
var obj = Py.Import(module_name);
Console.WriteLine(obj.InvokeMethod("replace"));
}else
throw new Exception("Invalid filename or file path");
}