ShellHelper.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.Diagnostics;
  3. using System.Collections.Generic;
  4. namespace ET
  5. {
  6. public static class ShellHelper
  7. {
  8. public static void Run(string cmd, string workDirectory, List<string> environmentVars = null)
  9. {
  10. Process process = new();
  11. try
  12. {
  13. #if UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX
  14. string app = "bash";
  15. string splitChar = ":";
  16. string arguments = "-c";
  17. #elif UNITY_EDITOR_WIN
  18. string app = "cmd.exe";
  19. string splitChar = ";";
  20. string arguments = "/c";
  21. #endif
  22. ProcessStartInfo start = new ProcessStartInfo(app);
  23. if (environmentVars != null)
  24. {
  25. foreach (string var in environmentVars)
  26. {
  27. start.EnvironmentVariables["PATH"] += (splitChar + var);
  28. }
  29. }
  30. process.StartInfo = start;
  31. start.Arguments = arguments + " \"" + cmd + "\"";
  32. start.CreateNoWindow = true;
  33. start.ErrorDialog = true;
  34. start.UseShellExecute = false;
  35. start.WorkingDirectory = workDirectory;
  36. if (start.UseShellExecute)
  37. {
  38. start.RedirectStandardOutput = false;
  39. start.RedirectStandardError = false;
  40. start.RedirectStandardInput = false;
  41. }
  42. else
  43. {
  44. start.RedirectStandardOutput = true;
  45. start.RedirectStandardError = true;
  46. start.RedirectStandardInput = true;
  47. start.StandardOutputEncoding = System.Text.Encoding.UTF8;
  48. start.StandardErrorEncoding = System.Text.Encoding.UTF8;
  49. }
  50. bool endOutput = false;
  51. bool endError = false;
  52. process.OutputDataReceived += (sender, args) =>
  53. {
  54. if (args.Data != null)
  55. {
  56. UnityEngine.Debug.Log(args.Data);
  57. }
  58. else
  59. {
  60. endOutput = true;
  61. }
  62. };
  63. process.ErrorDataReceived += (sender, args) =>
  64. {
  65. if (args.Data != null)
  66. {
  67. UnityEngine.Debug.LogError(args.Data);
  68. }
  69. else
  70. {
  71. endError = true;
  72. }
  73. };
  74. process.Start();
  75. process.BeginOutputReadLine();
  76. process.BeginErrorReadLine();
  77. while (!endOutput || !endError)
  78. {
  79. }
  80. process.CancelOutputRead();
  81. process.CancelErrorRead();
  82. }
  83. catch (Exception e)
  84. {
  85. UnityEngine.Debug.LogException(e);
  86. }
  87. finally
  88. {
  89. process.Close();
  90. }
  91. }
  92. }
  93. }