ShellHelper.cs 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. public static void Run(string cmd, string workDirectory, List<string> environmentVars = null)
  21. {
  22. Process p = null;
  23. try
  24. {
  25. ProcessStartInfo start = new ProcessStartInfo(shellApp);
  26. #if UNITY_EDITOR_OSX
  27. string splitChar = ":";
  28. start.Arguments = "-c";
  29. #elif UNITY_EDITOR_WIN
  30. string splitChar = ";";
  31. start.Arguments = "/c";
  32. #endif
  33. if (environmentVars != null)
  34. {
  35. foreach (string var in environmentVars)
  36. {
  37. start.EnvironmentVariables["PATH"] += (splitChar + var);
  38. }
  39. }
  40. start.Arguments += (" \"" + cmd + " \"");
  41. start.CreateNoWindow = true;
  42. start.ErrorDialog = true;
  43. start.UseShellExecute = false;
  44. start.WorkingDirectory = workDirectory;
  45. if (start.UseShellExecute)
  46. {
  47. start.RedirectStandardOutput = false;
  48. start.RedirectStandardError = false;
  49. start.RedirectStandardInput = false;
  50. }
  51. else
  52. {
  53. start.RedirectStandardOutput = true;
  54. start.RedirectStandardError = true;
  55. start.RedirectStandardInput = true;
  56. start.StandardOutputEncoding = System.Text.Encoding.UTF8;
  57. start.StandardErrorEncoding = System.Text.Encoding.UTF8;
  58. }
  59. p = Process.Start(start);
  60. p.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) { UnityEngine.Debug.LogError(e.Data); };
  61. p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) { UnityEngine.Debug.LogError(e.Data); };
  62. p.Exited += delegate(object sender, System.EventArgs e) { UnityEngine.Debug.LogError(e.ToString()); };
  63. bool hasError = false;
  64. do
  65. {
  66. string line = p.StandardOutput.ReadLine();
  67. if (line == null)
  68. {
  69. break;
  70. }
  71. line = line.Replace("\\", "/");
  72. UnityEngine.Debug.Log(line);
  73. }
  74. while (true);
  75. while (true)
  76. {
  77. string error = p.StandardError.ReadLine();
  78. if (string.IsNullOrEmpty(error))
  79. {
  80. break;
  81. }
  82. hasError = true;
  83. UnityEngine.Debug.LogError(error);
  84. }
  85. p.Close();
  86. if (hasError)
  87. {
  88. UnityEngine.Debug.LogError("has error!");
  89. }
  90. }
  91. catch (Exception e)
  92. {
  93. UnityEngine.Debug.LogException(e);
  94. if (p != null)
  95. {
  96. p.Close();
  97. }
  98. }
  99. }
  100. }
  101. }