PythonHelper.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace WWPipeLine.Commons
  8. {
  9. public class PythonHelp
  10. {
  11. public static string PythonPath
  12. {
  13. get
  14. {
  15. if (System.IO.File.Exists(Paths.ApplicationPy))
  16. {
  17. return Paths.ApplicationPy;
  18. }
  19. else
  20. {
  21. return "python.exe";
  22. }
  23. }
  24. }
  25. /// <summary>
  26. /// Python执行脚本
  27. /// </summary>
  28. /// <param name="type"></param>
  29. /// <param name="model"></param>
  30. ///
  31. /// <returns></returns>
  32. public static EnumHelper.EPyStatus RunPythonScripts(EnumHelper.EBusinessType type, object model)
  33. {
  34. var status = EnumHelper.EPyStatus.Normal;
  35. if (model == null)
  36. return EnumHelper.EPyStatus.ArgsError;
  37. Process p = new Process();//开启一个新进程
  38. try
  39. {
  40. string filepath = Paths.ApplicationPythonScripts + "InitServer.py";
  41. p.StartInfo.FileName = string.Format("\"{0}\" ", PythonPath.Replace("\\", "/"));
  42. string sArguments = string.Format(" \"{0}\" \"{1}\" {2} ", filepath, Newtonsoft.Json.JsonConvert.SerializeObject(model).Replace("\"", "\\\""), ((int)type).ToString());
  43. p.StartInfo.Arguments = sArguments;
  44. p.StartInfo.UseShellExecute = false;
  45. p.StartInfo.CreateNoWindow = true;
  46. p.Start();
  47. Commons.Cache.CurrentThreadID = p.Id;
  48. p.WaitForExit();
  49. status = (EnumHelper.EPyStatus)p.ExitCode;
  50. }
  51. catch (Exception ex)
  52. {
  53. string msg = string.Empty;
  54. switch (ex.GetType().Name)
  55. {
  56. case "Win32Exception":
  57. msg = "python环境异常";
  58. status = EnumHelper.EPyStatus.EnvError;
  59. break;
  60. case "NullReferenceException":
  61. msg = "python参数传递异常";
  62. LogHelper.Error("python参数传递异常," + ex);
  63. status = EnumHelper.EPyStatus.ArgsError;
  64. break;
  65. default:
  66. msg = "python执行异常";
  67. status = EnumHelper.EPyStatus.RunError;
  68. break;
  69. }
  70. LogHelper.Error(msg + "," + ex);
  71. }
  72. finally
  73. {
  74. p.Dispose();
  75. }
  76. Commons.Cache.CurrentThreadID = 0;
  77. return status;
  78. }
  79. }
  80. }