Beispiel #1
0
        public static string GetCommandsDisplayLabel(
            Microsoft.Build.Evaluation.Project project,
            IPythonProject2 projectNode
            )
        {
            var label = project.GetPropertyValue("PythonCommandsDisplayLabel") ?? string.Empty;

            var match = _customCommandLabelRegex.Match(label);

            if (match.Success)
            {
                label = LoadResourceFromAssembly(
                    match.Groups["assembly"].Value,
                    match.Groups["namespace"].Value,
                    match.Groups["key"].Value
                    );
            }

            if (string.IsNullOrEmpty(label))
            {
                return(SR.GetString(SR.PythonMenuLabel));
            }

            return(PerformSubstitutions(projectNode, label));
        }
Beispiel #2
0
        private static string PerformSubstitutions(IPythonProject2 project, string label)
        {
            return(Regex.Replace(label, @"\{(?<key>\w+)\}", m => {
                var key = m.Groups["key"].Value;
                if ("projectname".Equals(key, StringComparison.InvariantCultureIgnoreCase))
                {
                    return Path.ChangeExtension(project.ProjectFile, null);
                }
                else if ("projectfile".Equals(key, StringComparison.InvariantCultureIgnoreCase))
                {
                    return project.ProjectFile;
                }

                var instance = project.GetMSBuildProjectInstance();
                if (instance != null)
                {
                    var value = instance.GetPropertyValue(key);
                    if (!string.IsNullOrEmpty(value))
                    {
                        return value;
                    }
                }

                return m.Value;
            }));
        }
Beispiel #3
0
        public CommandStartInfo GetStartInfo(IPythonProject2 project)
        {
            var outputs = BuildTarget(project, _target);
            var config  = PythonProjectLaunchProperties.Create(project);

            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 = PythonProjectLaunchProperties.ParseEnvironment(item.GetMetadata(BuildTasks.CreatePythonCommandItem.EnvironmentKey)),
                TargetType           = item.GetMetadata(BuildTasks.CreatePythonCommandItem.TargetTypeKey),
                ExecuteIn            = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ExecuteInKey),
                RequiredPackages     = item.GetMetadata(BuildTasks.CreatePythonCommandItem.RequiredPackagesKey).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
            };

            try {
                startInfo.WorkingDirectory = CommonUtils.GetAbsoluteFilePath(project.ProjectHome, startInfo.WorkingDirectory);
            } catch (ArgumentException) {
            }

            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);
            }

            startInfo.EnvironmentVariables["PYTHONUNBUFFERED"] = "1";
            startInfo.AddPropertiesAfter(PythonProjectLaunchProperties.Create(project));

            Debug.Assert(!string.IsNullOrEmpty(startInfo.WorkingDirectory));
            Debug.Assert(Path.IsPathRooted(startInfo.WorkingDirectory));

            return(startInfo);
        }
Beispiel #4
0
 private async void RunInConsole(IPythonProject2 project, CommandStartInfo startInfo)
 {
     using (var process = ProcessOutput.Run(
                startInfo.Filename,
                new[] { startInfo.Arguments },
                startInfo.WorkingDirectory,
                startInfo.EnvironmentVariables,
                true,
                null,
                quoteArgs: false
                )) {
         await process;
     }
 }
Beispiel #5
0
        private async void RunInOutput(IPythonProject2 project, CommandStartInfo startInfo)
        {
            Redirector redirector = OutputWindowRedirector.GetGeneral(project.Site);

            if (startInfo.ErrorRegex != null || startInfo.WarningRegex != null)
            {
                redirector = new TeeRedirector(redirector, new ErrorListRedirector(_project.Site, project as IVsHierarchy, startInfo.WorkingDirectory, _errorListProvider, startInfo.ErrorRegex, startInfo.WarningRegex));
            }
            redirector.ShowAndActivate();

            using (var process = ProcessOutput.Run(
                       startInfo.Filename,
                       new[] { startInfo.Arguments },
                       startInfo.WorkingDirectory,
                       startInfo.EnvironmentVariables,
                       false,
                       redirector,
                       quoteArgs: false
                       )) {
                await process;
            }
        }
Beispiel #6
0
        private static IDictionary <string, TargetResult> BuildTarget(IPythonProject2 project, string target)
        {
            var config = project.GetMSBuildProjectInstance();

            if (config == null)
            {
                throw new ArgumentException("Project does not support MSBuild", "project");
            }

            IDictionary <string, TargetResult> outputs;

            var logger = new StringLogger();

#if DEBUG
            var loggers = new ILogger[] { new TraceLogger(), logger };
#else
            var loggers = new ILogger[] { logger };
#endif

            if (!config.Build(new[] { target }, loggers, Enumerable.Empty <ForwardingLoggerRecord>(), out outputs))
            {
                var outputWindow = OutputWindowRedirector.Get(
                    project.Site,
                    VSConstants.OutputWindowPaneGuid.BuildOutputPane_guid,
                    "Build"
                    );
                outputWindow.WriteErrorLine(SR.GetString(SR.ErrorBuildingCustomCommand, target));
                foreach (var line in logger.Lines)
                {
                    outputWindow.WriteErrorLine(line.TrimEnd('\r', '\n'));
                }
                throw new InvalidOperationException(SR.GetString(SR.ErrorBuildingCustomCommand, target));
            }

            return(outputs);
        }
Beispiel #7
0
        private async void RunInOutput(IPythonProject2 project, CommandStartInfo startInfo) {
            Redirector redirector = OutputWindowRedirector.GetGeneral(project.Site);
            if (startInfo.ErrorRegex != null || startInfo.WarningRegex != null) {
                redirector = new TeeRedirector(redirector, new ErrorListRedirector(_project.Site, project as IVsHierarchy, startInfo.WorkingDirectory, _errorListProvider, startInfo.ErrorRegex, startInfo.WarningRegex));
            }
            redirector.ShowAndActivate();

            using (var process = ProcessOutput.Run(
                startInfo.Filename,
                new[] { startInfo.Arguments },
                startInfo.WorkingDirectory,
                startInfo.EnvironmentVariables,
                false,
                redirector,
                quoteArgs: false
            )) {
                await process;
            }
        }
Beispiel #8
0
        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;
        }
Beispiel #9
0
        public CommandStartInfo GetStartInfo(IPythonProject2 project) {
            var outputs = BuildTarget(project, _target);
            var config = PythonProjectLaunchProperties.Create(project);

            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(Strings.ErrorBuildingCustomCommand.FormatUI(_target));
            }

            var startInfo = new CommandStartInfo {
                Filename = item.ItemSpec,
                Arguments = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ArgumentsKey),
                WorkingDirectory = item.GetMetadata(BuildTasks.CreatePythonCommandItem.WorkingDirectoryKey),
                EnvironmentVariables = PythonProjectLaunchProperties.ParseEnvironment(item.GetMetadata(BuildTasks.CreatePythonCommandItem.EnvironmentKey)),
                TargetType = item.GetMetadata(BuildTasks.CreatePythonCommandItem.TargetTypeKey),
                ExecuteIn = item.GetMetadata(BuildTasks.CreatePythonCommandItem.ExecuteInKey),
                RequiredPackages = item.GetMetadata(BuildTasks.CreatePythonCommandItem.RequiredPackagesKey).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
            };

            try {
                startInfo.WorkingDirectory = PathUtils.GetAbsoluteFilePath(project.ProjectHome, startInfo.WorkingDirectory);
            } catch (ArgumentException) {
            }

            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);
            }

            startInfo.EnvironmentVariables["PYTHONUNBUFFERED"] = "1";
            startInfo.AddPropertiesAfter(PythonProjectLaunchProperties.Create(project));

            Debug.Assert(!string.IsNullOrEmpty(startInfo.WorkingDirectory));
            Debug.Assert(Path.IsPathRooted(startInfo.WorkingDirectory));

            return startInfo;
        }
Beispiel #10
0
        private static IDictionary<string, TargetResult> BuildTarget(IPythonProject2 project, string target) {
            var config = project.GetMSBuildProjectInstance();
            if (config == null) {
                throw new ArgumentException("Project does not support MSBuild", "project");
            }

            IDictionary<string, TargetResult> outputs;

            var logger = new StringLogger();
#if DEBUG
            var loggers = new ILogger[] { new TraceLogger(), logger };
#else
            var loggers = new ILogger[] { logger };
#endif

            if (!config.Build(new[] { target }, loggers, Enumerable.Empty<ForwardingLoggerRecord>(), out outputs)) {
                var outputWindow = OutputWindowRedirector.Get(
                    project.Site,
                    VSConstants.OutputWindowPaneGuid.BuildOutputPane_guid,
                    "Build"
                );
                outputWindow.WriteErrorLine(Strings.ErrorBuildingCustomCommand.FormatUI(target));
                foreach (var line in logger.Lines) {
                    outputWindow.WriteErrorLine(line.TrimEnd('\r', '\n'));
                }
                throw new InvalidOperationException(Strings.ErrorBuildingCustomCommand.FormatUI(target));
            }

            return outputs;
        }
Beispiel #11
0
        public static string GetCommandsDisplayLabel(
            Microsoft.Build.Evaluation.Project project,
            IPythonProject2 projectNode
        ) {
            var label = project.GetPropertyValue("PythonCommandsDisplayLabel") ?? string.Empty;
            
            var match = _customCommandLabelRegex.Match(label);
            if (match.Success) {
                label = LoadResourceFromAssembly(
                    match.Groups["assembly"].Value,
                    match.Groups["namespace"].Value,
                    match.Groups["key"].Value
                );
            }

            if (string.IsNullOrEmpty(label)) {
                return Strings.PythonMenuLabel;
            }

            return PerformSubstitutions(projectNode, label);
        }
Beispiel #12
0
        private static string PerformSubstitutions(IPythonProject2 project, string label) {
            return Regex.Replace(label, @"\{(?<key>\w+)\}", m => {
                var key = m.Groups["key"].Value;
                if ("projectname".Equals(key, StringComparison.InvariantCultureIgnoreCase)) {
                    return Path.ChangeExtension(project.ProjectFile, null);
                } else if ("projectfile".Equals(key, StringComparison.InvariantCultureIgnoreCase)) {
                    return project.ProjectFile;
                }

                var instance = project.GetMSBuildProjectInstance();
                if (instance != null) {
                    var value = instance.GetPropertyValue(key);
                    if (!string.IsNullOrEmpty(value)) {
                        return value;
                    }
                }

                return m.Value;
            });
        }
Beispiel #13
0
        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);
        }
Beispiel #14
0
        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);
        }
Beispiel #15
0
 private async void RunInConsole(IPythonProject2 project, CommandStartInfo startInfo) {
     using (var process = ProcessOutput.Run(
         startInfo.Filename,
         new[] { startInfo.Arguments },
         startInfo.WorkingDirectory,
         startInfo.EnvironmentVariables,
         true,
         null,
         quoteArgs: false
     )) {
         await process;
     }
 }
 public static IPythonProjectLaunchProperties Create(IPythonProject2 project) {
     return Create(project, project.Site, null);
 }
 public static IPythonProjectLaunchProperties Create(IPythonProject2 project)
 {
     return(Create(project, project.Site, null));
 }