浏览代码

Improve try catch and add var

/pyrception-integration
leopoldo-zugasti 3 年前
当前提交
e996220c
共有 2 个文件被更改,包括 163 次插入138 次删除
  1. 4
      com.unity.perception/Editor/Visualizer/PythonForUnityInstaller.cs
  2. 297
      com.unity.perception/Editor/Visualizer/VisualizerInstaller.cs

4
com.unity.perception/Editor/Visualizer/PythonForUnityInstaller.cs


{
if (!CheckIfPackageInstalled())
{
AddRequest request = Client.Add("com.unity.scripting.python@4.0.0-exp.5");
var request = Client.Add("com.unity.scripting.python@4.0.0-exp.5");
while (!request.IsCompleted)
{

static bool CheckIfPackageInstalled()
{
ListRequest request = Client.List();
var request = Client.List();
while (!request.IsCompleted)
{
Thread.Sleep(100);

297
com.unity.perception/Editor/Visualizer/VisualizerInstaller.cs


{
public class VisualizerInstaller : EditorWindow
{
//This files stores entries as ProjectDataPath,PythonPID,Port,VisualizerPID
//It keeps a record of the instances of visualizer opened so that we don't open a new one everytime
const string k_FilenameStreamlitInstances = "Unity/streamlit_instances.csv";

get
{
#if UNITY_EDITOR_WIN
#if UNITY_EDITOR_WIN
#elif UNITY_EDITOR_OSX
#elif UNITY_EDITOR_OSX
#endif
#endif
#if UNITY_EDITOR_OSX
#if UNITY_EDITOR_OSX
#elif UNITY_EDITOR_WIN
#elif UNITY_EDITOR_WIN
#endif
#endif
// ReSharper disable Unity.PerformanceAnalysis
/// <summary>

var (pythonPid, port, visualizerPid) = ReadEntry(project);
//If there is a python instance for this project AND it is alive then setup will fail (must kill instance)
if(pythonPid != -1 && ProcessAlive(pythonPid, port, visualizerPid))
if (pythonPid != -1 && ProcessAlive(pythonPid, port, visualizerPid))
{
if (EditorUtility.DisplayDialog("Kill visualizer?",
"The visualizer tool can't be running while you setup, would you like to kill the current instance?",

}
}
#if UNITY_EDITOR_WIN
var packagesPath = Path.GetFullPath(Application.dataPath.Replace("/Assets","/Library/PythonInstall/Scripts"));
#elif UNITY_EDITOR_OSX
#if UNITY_EDITOR_WIN
var packagesPath = Path.GetFullPath(Application.dataPath.Replace("/Assets", "/Library/PythonInstall/Scripts"));
#elif UNITY_EDITOR_OSX
#endif
#endif
#if UNITY_EDITOR_WIN
#if UNITY_EDITOR_WIN
#endif
#endif
#if UNITY_EDITOR_WIN
#if UNITY_EDITOR_WIN
#elif UNITY_EDITOR_OSX
#elif UNITY_EDITOR_OSX
#endif
if (exitCode != 0) {
#endif
if (exitCode != 0)
{
Debug.Log("Successfully installed visualizer");
Debug.Log("Successfully installed visualizer");
}
/// <summary>

info.RedirectStandardError = waitForExit > 0;
var cmd = Process.Start(info);
if (cmd == null)
{
Debug.LogError($"Could not create process using command {command}");
return 0;
}
if (cmd != null) return cmd.Id;
break;
return cmd.Id;
cmd?.WaitForExit();
cmd.WaitForExit();
if(waitForExit > 0)
if (waitForExit > 0)
cmd?.WaitForExit(waitForExit);
cmd.WaitForExit(waitForExit);
if (getOutput && waitForExit != 0) {
output = cmd?.StandardOutput.ReadToEnd();
if (getOutput && waitForExit != 0)
{
output = cmd.StandardOutput.ReadToEnd();
if (cmd != null && cmd.HasExited){
if (cmd.HasExited)
{
exitCode = cmd.ExitCode;
if (exitCode != 0)
{

return 0;
}
// ReSharper disable Unity.PerformanceAnalysis
/// <summary>
/// If an instance is already running for this project it opens the browser at the correct port

var (pythonPid, port, visualizerPid) = ReadEntry(project);
EditorUtility.DisplayProgressBar("Opening Visualizer", "Checking if instance exists", 0.5f / 4);
if(pythonPid != -1 && ProcessAlive(pythonPid, port, visualizerPid))
if (pythonPid != -1 && ProcessAlive(pythonPid, port, visualizerPid))
//Otherwise delete any previous entry for this project and launch a new process
else
{

EditorUtility.DisplayProgressBar("Opening Visualizer", "Running executable", 1f / 4);
var errorCode = ExecuteVisualizer();
if(errorCode == -1)
if (errorCode == -1)
Process[] after;
const int maxAttempts = 5;

var newVisualizerPid = -1;
var attempts = 0;
while(newVisualizerPid == -1)
while (newVisualizerPid == -1)
if(attempts == maxAttempts)
if (attempts == maxAttempts)
attempts++;
}

attempts = 0;
while(newPythonPid == -1)
while (newPythonPid == -1)
if(attempts == maxAttempts)
if (attempts == maxAttempts)
attempts++;
}

attempts = 0;
while(newPort == -1)
while (newPort == -1)
if(attempts == maxAttempts)
if (attempts == maxAttempts)
attempts++;
}

EditorUtility.DisplayProgressBar("Opening Visualizer", "Opening", 4f / 4);
LaunchBrowser(newPort);
EditorUtility.ClearProgressBar();
}
}

static int ExecuteVisualizer()
{
#if UNITY_EDITOR_WIN
var packagesPath = Path.GetFullPath(Application.dataPath.Replace("/Assets","/Library/PythonInstall/Scripts"));
#elif UNITY_EDITOR_OSX
#if UNITY_EDITOR_WIN
var packagesPath = Path.GetFullPath(Application.dataPath.Replace("/Assets", "/Library/PythonInstall/Scripts"));
#elif UNITY_EDITOR_OSX
#endif
#endif
#if UNITY_EDITOR_WIN
#if UNITY_EDITOR_WIN
#endif
#endif
#if UNITY_EDITOR_WIN
#if UNITY_EDITOR_WIN
#elif UNITY_EDITOR_OSX
#elif UNITY_EDITOR_OSX
#endif
#endif
string output = null;
var exitCode = 0;

Debug.LogError("Problem occured when launching the visualizer - Exit Code: " + exitCode);
return -1;
}
return pid;
}

return (-1,-1,-1);
return (-1, -1, -1);
using (var sr = File.OpenText(PathToStreamlitInstances))
{

var entry = line.TrimEnd().Split(',');
if(entry[0] == project)
if (entry[0] == project)
return (int.Parse(entry[1]) -1, int.Parse(entry[2]), int.Parse(entry[3]) -1);
return (int.Parse(entry[1]) - 1, int.Parse(entry[2]), int.Parse(entry[3]) - 1);
return (-1,-1,-1);
return (-1, -1, -1);
}
static void WriteEntry(string project, int pythonId, int port, int visualizerId)

entries = entries.FindAll(x => !x.StartsWith(project));
using (var sw = File.CreateText(path))
{
foreach(var entry in entries)
foreach (var entry in entries)
{
sw.WriteLine(entry.TrimEnd());
}

/// <returns></returns>
static int GetNewProcessID(Process[] before, Process[] after, string name)
{
foreach(var p in after)
foreach (var p in after)
// try/catch to skip any process that may not exist anymore
// try/catch to skip any process that may:
// not exist anymore/may be on another computer/are not associated with a living process
try
{
if (p.ProcessName.ToLower().Contains(name.ToLower()))

break;
}
}
if (isNew)
{
return p.Id;

catch
catch(Exception ex)
// ignored
if (!(ex is InvalidOperationException || ex is NotSupportedException))
{
throw;
}
return -1;
}

/// <returns></returns>
static int GetPortForPid(int pid)
{
foreach(var p in ProcessPorts.ProcessPortMap)
foreach (var p in ProcessPorts.ProcessPortMap)
if(p.ProcessId == pid)
if (p.ProcessId == pid)
return -1;
}

/// <returns></returns>
static bool PidExists(int pid)
{
try
{
try
{
else
{
return true;
}
}
catch (ArgumentException)
{
return true;
}
catch (ArgumentException)
{
}
}
}
/// <summary>

{
var processPorts = new List<ProcessPort>();
try
{
var startInfo = new ProcessStartInfo();
var startInfo = new ProcessStartInfo();
startInfo.FileName = "netstat.exe";
startInfo.Arguments = "-a -n -o";
startInfo.FileName = "netstat.exe";
startInfo.Arguments = "-a -n -o";
startInfo.FileName = "netstat";
startInfo.Arguments = "-n -v -a";
startInfo.FileName = "netstat";
startInfo.Arguments = "-n -v -a";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
using (var proc = new Process())
{
proc.StartInfo = startInfo;
proc.Start();
using (var proc = new Process())
{
proc.StartInfo = startInfo;
proc.Start();
proc.WaitForExit(2500);
proc.WaitForExit(2500);
var standardOutput = proc.StandardOutput;
var standardError = proc.StandardError;
var standardOutput = proc.StandardOutput;
var standardError = proc.StandardError;
var netStatContent = standardOutput.ReadToEnd() + standardError.ReadToEnd();
var netStatExitStatus = proc.ExitCode.ToString();
var netStatContent = standardOutput.ReadToEnd() + standardError.ReadToEnd();
var netStatExitStatus = proc.ExitCode.ToString();
if (netStatExitStatus != "0")
{
Debug.LogError("NetStat command failed. This may require elevated permissions.");
}
if (netStatExitStatus != "0")
{
Debug.LogError("NetStat command failed. This may require elevated permissions.");
}
var netStatRows = Regex.Split(netStatContent, "\r\n");
var netStatRows = Regex.Split(netStatContent, "\r\n");
foreach (var netStatRow in netStatRows)
{
var tokens = Regex.Split(netStatRow, "\\s+");
foreach (var netStatRow in netStatRows)
{
var tokens = Regex.Split(netStatRow, "\\s+");
if (tokens.Length > 4 && (tokens[1].Equals("UDP") || tokens[1].Equals("TCP")))
if (tokens.Length > 4 && (tokens[1].Equals("UDP") || tokens[1].Equals("TCP")))
{
var ipAddress = Regex.Replace(tokens[2], @"\[(.*?)\]", "1.1.1.1");
try
var ipAddress = Regex.Replace(tokens[2], @"\[(.*?)\]", "1.1.1.1");
try
{
processPorts.Add(new ProcessPort(
tokens[1] == "UDP" ? Convert.ToInt32(tokens[4]) : Convert.ToInt32(tokens[5]),
Convert.ToInt32(ipAddress.Split(':')[1])
));
}
catch
processPorts.Add(new ProcessPort(
tokens[1] == "UDP" ? Convert.ToInt32(tokens[4]) : Convert.ToInt32(tokens[5]),
Convert.ToInt32(ipAddress.Split(':')[1])
));
}
catch (Exception ex)
{
if (ex is IndexOutOfRangeException || ex is FormatException || ex is OverflowException)
else
{
throw;
}
else
}
else
{
if (!netStatRow.Trim().StartsWith("Proto") && !netStatRow.Trim().StartsWith("Active") && !String.IsNullOrWhiteSpace(netStatRow))
if (!netStatRow.Trim().StartsWith("Proto") && !netStatRow.Trim().StartsWith("Active") && !String.IsNullOrWhiteSpace(netStatRow))
{
Debug.LogError("Unrecognized NetStat row to a Process to Port mapping.");
Debug.LogError(netStatRow);
}
Debug.LogError("Unrecognized NetStat row to a Process to Port mapping.");
Debug.LogError(netStatRow);
}
if(tokens[5] != "CLOSED"){
if(tokens[5] != "CLOSED")
{
processPorts.Add(new ProcessPort(
Convert.ToInt32(tokens[8]),
Convert.ToInt32(tokens[3].Split('.')[1])

catch (FormatException)
{
//On mac rows show up in a difficult to predict order of formats (this skips all rows that we don't care about)
catch
catch (Exception ex)
Debug.LogError("Could not convert the following NetStat row to a Process to Port mapping.");
Debug.LogError(netStatRow);
if (ex is IndexOutOfRangeException || ex is OverflowException)
{
Debug.LogError("Could not convert the following NetStat row to a Process to Port mapping.");
Debug.LogError(netStatRow);
}
else
{
throw;
}
}
catch (Exception ex)
{
Debug.LogError(ex.Message);
}
return processPorts;
}
}

/// </summary>
/// <param name="processId"></param>
/// <param name="portNumber"></param>
internal ProcessPort (int processId, int portNumber)
internal ProcessPort(int processId, int portNumber)
{
ProcessId = processId;
PortNumber = portNumber;

{
SetupVisualizer();
}
var packagesPath = Path.GetFullPath(Application.dataPath.Replace("/Assets","/Library/PythonInstall/Scripts"));
var packagesPath = Path.GetFullPath(Application.dataPath.Replace("/Assets", "/Library/PythonInstall/Scripts"));
#elif UNITY_EDITOR_OSX
string packagesPath = Path.GetFullPath(Application.dataPath.Replace("/Assets","/Library/PythonInstall/bin"));
#endif

#elif UNITY_EDITOR_OSX
ExecuteCmd($"cd \'{packagesPath}\'; ./python3.7 -m pip show unity-cv-datasetvisualizer", ref exitCode, ref output, waitForExit: 1500, getOutput: true);
#endif
if (exitCode != 0) {
if (exitCode != 0)
{
Debug.LogError("Could not get the version of the current install of the visualizer tool");
return;
}

if (currentVersion == null) {
if (currentVersion == null)
{
if(PipAPI.CompareVersions(latestVersion, currentVersion) > 0)
if (PipAPI.CompareVersions(latestVersion, currentVersion) > 0)
{
if (EditorUtility.DisplayDialog("Update Found for Visualizer",
$"An update was found for the Visualizer",

static bool CheckIfVisualizerInstalled()
{
#if UNITY_EDITOR_WIN
var packagesPath = Path.GetFullPath(Application.dataPath.Replace("/Assets","/Library/PythonInstall/Scripts"));
var packagesPath = Path.GetFullPath(Application.dataPath.Replace("/Assets", "/Library/PythonInstall/Scripts"));
#elif UNITY_EDITOR_OSX
var packagesPath = Path.GetFullPath(Application.dataPath.Replace("/Assets","/Library/PythonInstall/bin"));
#endif

#elif UNITY_EDITOR_OSX
ExecuteCmd($"cd \'{packagesPath}\'; ./python3.7 -m pip list", ref exitCode, ref output, waitForExit: 1500, getOutput: true);
#endif
if (exitCode != 0) {
if (exitCode != 0)
{
Debug.LogError("Could not list pip packages");
return false;
}

正在加载...
取消
保存