ShellHelper.cs 3.4 KB

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