private async Task <bool> RunInRepl(IPythonProject2 project, CommandStartInfo startInfo) { var executeIn = string.IsNullOrEmpty(startInfo.ExecuteIn) ? CreatePythonCommandItem.ExecuteInRepl : startInfo.ExecuteIn; bool resetRepl = executeIn.StartsWith("R", StringComparison.InvariantCulture); var replTitle = executeIn.Substring(4).TrimStart(' ', ':'); if (string.IsNullOrEmpty(replTitle)) { replTitle = SR.GetString(SR.CustomCommandReplTitle, DisplayLabelWithoutAccessKeys); } else { var match = _customCommandLabelRegex.Match(replTitle); if (match.Success) { replTitle = LoadResourceFromAssembly( match.Groups["assembly"].Value, match.Groups["namespace"].Value, match.Groups["key"].Value ); } } replTitle = PerformSubstitutions(project, replTitle); var replWindowId = PythonReplEvaluatorProvider.GetConfigurableReplId(ReplId + executeIn.Substring(4)); var model = _project.Site.GetComponentModel(); var replProvider = model.GetService <IReplWindowProvider>(); if (replProvider == null) { return(false); } var replWindow = replProvider.FindReplWindow(replWindowId); bool created = replWindow == null; if (created) { replWindow = replProvider.CreateReplWindow( _project.Site.GetPythonContentType(), replTitle, typeof(PythonLanguageInfo).GUID, replWindowId ); } var replToolWindow = replWindow as ToolWindowPane; var replFrame = (replToolWindow != null) ? replToolWindow.Frame as IVsWindowFrame : null; var pyEvaluator = replWindow.Evaluator as PythonReplEvaluator; var options = (pyEvaluator != null) ? pyEvaluator.CurrentOptions as ConfigurablePythonReplOptions : null; if (options == null) { if (created && replFrame != null) { // We created the window, but it isn't valid, so we'll close // it again immediately. replFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } return(false); } if (pyEvaluator.IsExecuting) { throw new InvalidOperationException(SR.GetString(SR.ErrorCommandAlreadyRunning)); } options.InterpreterFactory = project.GetInterpreterFactory(); options.Project = project as PythonProjectNode; options._workingDir = startInfo.WorkingDirectory; options._envVars = startInfo.EnvironmentVariables; project.AddActionOnClose((object)replWindow, BasePythonReplEvaluator.CloseReplWindow); var pane = replWindow as ToolWindowPane; var frame = pane != null ? pane.Frame as IVsWindowFrame : null; if (frame != null) { ErrorHandler.ThrowOnFailure(frame.Show()); } var result = await pyEvaluator.Reset(quiet : true); if (result.IsSuccessful) { try { var filename = startInfo.Filename; var arguments = startInfo.Arguments; if (startInfo.IsScript) { pyEvaluator.Window.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments)); Debug.WriteLine("Executing {0} {1}", filename, arguments); result = await pyEvaluator.ExecuteFile(filename, arguments); } else if (startInfo.IsModule) { pyEvaluator.Window.WriteLine(string.Format("Executing -m {0} {1}", filename, arguments)); Debug.WriteLine("Executing -m {0} {1}", filename, arguments); result = await pyEvaluator.ExecuteModule(filename, arguments); } else if (startInfo.IsCode) { Debug.WriteLine("Executing -c \"{0}\"", filename, arguments); result = await pyEvaluator.ExecuteText(filename); } else { pyEvaluator.Window.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments)); Debug.WriteLine("Executing {0} {1}", filename, arguments); result = await pyEvaluator.ExecuteProcess(filename, arguments); } if (resetRepl) { // We really close the backend, rather than resetting. pyEvaluator.Close(); } } catch (Exception ex) { ActivityLog.LogError(SR.ProductName, SR.GetString(SR.ErrorRunningCustomCommand, _label, ex)); var outWindow = OutputWindowRedirector.GetGeneral(project.Site); if (outWindow != null) { outWindow.WriteErrorLine(SR.GetString(SR.ErrorRunningCustomCommand, _label, ex)); outWindow.Show(); } } return(true); } return(false); }
private async Task<bool> RunInRepl(IPythonProject2 project, CommandStartInfo startInfo) { var executeIn = string.IsNullOrEmpty(startInfo.ExecuteIn) ? CreatePythonCommandItem.ExecuteInRepl : startInfo.ExecuteIn; bool resetRepl = executeIn.StartsWith("R", StringComparison.InvariantCulture); var replTitle = executeIn.Substring(4).TrimStart(' ', ':'); if (string.IsNullOrEmpty(replTitle)) { replTitle = Strings.CustomCommandReplTitle.FormatUI(DisplayLabelWithoutAccessKeys); } else { var match = _customCommandLabelRegex.Match(replTitle); if (match.Success) { replTitle = LoadResourceFromAssembly( match.Groups["assembly"].Value, match.Groups["namespace"].Value, match.Groups["key"].Value ); } } replTitle = PerformSubstitutions(project, replTitle); var replWindowId = PythonReplEvaluatorProvider.GetConfigurableReplId(ReplId + executeIn.Substring(4)); var model = _project.Site.GetComponentModel(); var replProvider = model.GetService<InteractiveWindowProvider>(); if (replProvider == null) { return false; } var replWindow = replProvider.FindReplWindow(replWindowId); bool created = replWindow == null; if (created) { replWindow = replProvider.CreateInteractiveWindow( _project.Site.GetPythonContentType(), replTitle, typeof(PythonLanguageInfo).GUID, replWindowId ); } var replToolWindow = replWindow as ToolWindowPane; var replFrame = (replToolWindow != null) ? replToolWindow.Frame as IVsWindowFrame : null; var pyEvaluator = replWindow.InteractiveWindow.Evaluator as PythonReplEvaluator; var options = (pyEvaluator != null) ? pyEvaluator.CurrentOptions as ConfigurablePythonReplOptions : null; if (options == null) { if (created && replFrame != null) { // We created the window, but it isn't valid, so we'll close // it again immediately. replFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } return false; } if (pyEvaluator.IsExecuting) { throw new InvalidOperationException(Strings.ErrorCommandAlreadyRunning); } var ipp3 = project as IPythonProject3; if (ipp3 != null) { options.InterpreterFactory = ipp3.GetInterpreterFactoryOrThrow(); } else { options.InterpreterFactory = project.GetInterpreterFactory(); } options.Project = project as PythonProjectNode; options._workingDir = startInfo.WorkingDirectory; options._envVars = startInfo.EnvironmentVariables; project.AddActionOnClose((object)replWindow, BasePythonReplEvaluator.CloseReplWindow); var pane = replWindow as ToolWindowPane; var frame = pane != null ? pane.Frame as IVsWindowFrame : null; if (frame != null) { ErrorHandler.ThrowOnFailure(frame.Show()); } var result = await pyEvaluator.Reset(quiet: true); if (result.IsSuccessful) { try { var filename = startInfo.Filename; var arguments = startInfo.Arguments ?? string.Empty; if (startInfo.IsScript) { pyEvaluator.Window.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments)); Debug.WriteLine("Executing {0} {1}", filename, arguments); result = await pyEvaluator.ExecuteFile(filename, arguments); } else if (startInfo.IsModule) { pyEvaluator.Window.WriteLine(string.Format("Executing -m {0} {1}", filename, arguments)); Debug.WriteLine("Executing -m {0} {1}", filename, arguments); result = await pyEvaluator.ExecuteModule(filename, arguments); } else if (startInfo.IsCode) { Debug.WriteLine("Executing -c \"{0}\"", filename, arguments); result = await pyEvaluator.ExecuteText(filename); } else { pyEvaluator.Window.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments)); Debug.WriteLine("Executing {0} {1}", filename, arguments); result = await pyEvaluator.ExecuteProcess(filename, arguments); } if (resetRepl) { // We really close the backend, rather than resetting. pyEvaluator.Close(); } } catch (Exception ex) { ActivityLog.LogError(Strings.ProductTitle, Strings.ErrorRunningCustomCommand.FormatUI(_label, ex)); var outWindow = OutputWindowRedirector.GetGeneral(project.Site); if (outWindow != null) { outWindow.WriteErrorLine(Strings.ErrorRunningCustomCommand.FormatUI(_label, ex)); outWindow.Show(); } } return true; } return false; }
public CommandStartInfo GetStartInfo(IPythonProject2 project) { var outputs = BuildTarget(project, _target); var item = outputs.Values .SelectMany(result => result.Items) .FirstOrDefault(i => !string.IsNullOrEmpty(i.ItemSpec) && !string.IsNullOrEmpty(i.GetMetadata(BuildTasks.CreatePythonCommandItem.TargetTypeKey)) ); if (item == null) { throw new InvalidOperationException(SR.GetString(SR.ErrorBuildingCustomCommand, _target)); } var startInfo = new CommandStartInfo { Filename = item.ItemSpec, Arguments = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ArgumentsKey), WorkingDirectory = item.GetMetadata(BuildTasks.CreatePythonCommandItem.WorkingDirectoryKey), EnvironmentVariables = new Dictionary <string, string>(), TargetType = item.GetMetadata(BuildTasks.CreatePythonCommandItem.TargetTypeKey), ExecuteIn = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ExecuteInKey), RequiredPackages = item.GetMetadata(BuildTasks.CreatePythonCommandItem.RequiredPackagesKey).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) }; string errorRegex = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ErrorRegexKey); if (!string.IsNullOrEmpty(errorRegex)) { startInfo.ErrorRegex = new Regex(errorRegex); } string warningRegex = item.GetMetadata(BuildTasks.CreatePythonCommandItem.WarningRegexKey); if (!string.IsNullOrEmpty(warningRegex)) { startInfo.WarningRegex = new Regex(warningRegex); } // Fill PYTHONPATH from interpreter settings before we load values from Environment metadata item, // so that commands can explicitly override it if they want to. var pythonPathVarName = project.GetInterpreterFactory().Configuration.PathEnvironmentVariable; if (!string.IsNullOrWhiteSpace(pythonPathVarName)) { var pythonPath = string.Join(";", project.GetSearchPaths()); if (!_project.Site.GetPythonToolsService().GeneralOptions.ClearGlobalPythonPath) { pythonPath += ";" + Environment.GetEnvironmentVariable(pythonPathVarName); } startInfo.EnvironmentVariables[pythonPathVarName] = pythonPath; } // Fill other environment variables from project properties. string userEnv = project.GetProperty(PythonConstants.EnvironmentSetting); if (userEnv != null) { foreach (var envVar in userEnv.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) { var nameValue = envVar.Split(new[] { '=' }, 2); if (nameValue.Length == 2) { startInfo.EnvironmentVariables[nameValue[0]] = nameValue[1]; } } } var environment = item.GetMetadata(BuildTasks.CreatePythonCommandItem.EnvironmentKey); foreach (var line in environment.Split('\r', '\n')) { int equals = line.IndexOf('='); if (equals > 0) { startInfo.EnvironmentVariables[line.Substring(0, equals)] = line.Substring(equals + 1); } } startInfo.EnvironmentVariables["PYTHONUNBUFFERED"] = "1"; if (string.IsNullOrEmpty(startInfo.WorkingDirectory)) { startInfo.WorkingDirectory = project.ProjectHome ?? string.Empty; } else if (!Path.IsPathRooted(startInfo.WorkingDirectory)) { startInfo.WorkingDirectory = CommonUtils.GetAbsoluteDirectoryPath(project.ProjectHome, startInfo.WorkingDirectory); } return(startInfo); }