1 public class PythonExecuter
2 {
3 private readonly string _pythonDllPath;
4 private readonly string _workDir;
5
6 public PythonExecuter(string dllPath, string workDir)
7 {
8 _pythonDllPath = dllPath;
9 _workDir = workDir;
10 }
11
12 public async Task<bool> ExecutePythonScript(string scriptName)
13 {
14 bool result = false;
15 Runtime.PythonDLL = _pythonDllPath;
16 PythonEngine.Initialize();
17 dynamic sys = Py.Import("sys");
18 sys.path.append(_workDir);
19 PythonEngine.BeginAllowThreads();
20 await Task.Run(() =>
21 {
22 try
23 {
24 using (Py.GIL())
25 {
26 Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} python脚本准备执行");
27 dynamic testModule = Py.Import(scriptName);// 导入模块(传入py文件名即可)
28 dynamic py = testModule.main();// 执行该py脚本的main函数
29 Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} 执行python脚本成功,返回值:{py}");
30 result = (int)py == 0;
31 }
32 }
33 catch (Exception ex)
34 {
35 Console.WriteLine(ex.ToString());
36 }
37 });
38
39 AppContext.SetSwitch("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", true);
40 PythonEngine.Shutdown();
41 AppContext.SetSwitch("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", false);
42
43 return result;
44 }
45 }