コード例 #1
0
        private void StartInterpreter_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var view    = (EnvironmentView)e.Parameter;
            var factory = view.Factory;

            var psi = new ProcessStartInfo();

            psi.UseShellExecute = false;

            psi.FileName = e.Command == EnvironmentPathsExtension.StartInterpreter ?
                           factory.Configuration.InterpreterPath :
                           factory.Configuration.WindowsInterpreterPath;
            psi.WorkingDirectory = factory.Configuration.PrefixPath;

            // TODO: Figure out some other wa to get the project
            //var provider = _service.KnownProviders.OfType<LoadedProjectInterpreterFactoryProvider>().FirstOrDefault();
            //var vsProject = provider == null ?
            //    null :
            //    provider.GetProject(factory);
            IPythonProject project = null;// vsProject == null ? null : vsProject.GetPythonProject();

            if (project != null)
            {
                psi.EnvironmentVariables[factory.Configuration.PathEnvironmentVariable] =
                    string.Join(";", project.GetSearchPaths());
            }
            else
            {
                psi.EnvironmentVariables[factory.Configuration.PathEnvironmentVariable] = string.Empty;
            }

            Process.Start(psi).Dispose();
        }
コード例 #2
0
        internal static void AddSearchPaths(
            Dictionary <string, string> env,
            IPythonProject project,
            IServiceProvider provider = null
            )
        {
            var pathEnv = project.GetProjectAnalyzer().InterpreterFactory.Configuration.PathEnvironmentVariable;
            var paths   = new List <string>();

            string path;

            if (env.TryGetValue(pathEnv, out path))
            {
                paths.AddRange(path.Split(Path.PathSeparator));
            }

            paths.AddRange(EnumerateSearchPaths(project));

            if (provider != null && !provider.GetPythonToolsService().GeneralOptions.ClearGlobalPythonPath)
            {
                paths.AddRange((Environment.GetEnvironmentVariable(pathEnv) ?? "")
                               .Split(Path.PathSeparator)
                               .Where(p => !paths.Contains(p))
                               .ToList());
            }

            env[pathEnv] = string.Join(
                Path.PathSeparator.ToString(),
                paths
                );
        }
コード例 #3
0
        private static string PerformSubstitutions(IPythonProject 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;
            }));
        }
コード例 #4
0
        public DefaultPythonLauncherOptions(IPythonProject properties) {
            _properties = properties;
            InitializeComponent();

            _debugGroup.Visible = true;
            _mixedMode.Visible = true;
        }
コード例 #5
0
        internal static string DoSubstitutions(LaunchConfiguration original, IPythonProject project, string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(str);
            }

            return(SubstitutionPattern.Replace(
                       str,
                       m => {
                switch (m.Groups[1].Value.ToLowerInvariant())
                {
                case "startupfile":
                    return original.ScriptName;

                case "startupmodule":
                    try {
                        return ModulePath.FromFullPath(original.ScriptName, project.ProjectHome).ModuleName;
                    } catch (ArgumentException) {
                    }
                    break;
                }
                return m.Value;
            }
                       ));
        }
コード例 #6
0
        public static string GetCommandsDisplayLabel(
            Microsoft.Build.Evaluation.Project project,
            IPythonProject 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));
        }
コード例 #7
0
ファイル: DefaultPythonLauncher.cs プロジェクト: wenh123/PTVS
        public DefaultPythonLauncher(IServiceProvider serviceProvider, PythonToolsService pyService, IPythonProject/*!*/ project) {
            Utilities.ArgumentNotNull("project", project);

            _serviceProvider = serviceProvider;
            _pyService = pyService;
            _project = project;
        }
コード例 #8
0
        public override void DoCommand(object sender, EventArgs args)
        {
            if (!Utilities.SaveDirtyFiles())
            {
                // Abort
                return;
            }

            // Launch with project context if there is one and it contains the active document
            // Fallback to using default python project
            var file = CommonPackage.GetActiveTextView(_serviceProvider).GetFilePath();
            var pythonProjectNode = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;

            if ((pythonProjectNode != null) && (pythonProjectNode.FindNodeByFullPath(file) == null))
            {
                pythonProjectNode = null;
            }
            IPythonProject pythonProject = pythonProjectNode as IPythonProject ?? new DefaultPythonProject(_serviceProvider, file);

            var launcher = PythonToolsPackage.GetLauncher(_serviceProvider, pythonProject);

            try {
                launcher.LaunchFile(file, CommandId == CommonConstants.StartDebuggingCmdId);
            } catch (NoInterpretersException ex) {
                PythonToolsPackage.OpenNoInterpretersHelpPage(_serviceProvider, ex.HelpPage);
            }
        }
コード例 #9
0
ファイル: DefaultPythonLauncher.cs プロジェクト: krus/PTVS
        public DefaultPythonLauncher(IServiceProvider serviceProvider, PythonToolsService pyService, IPythonProject /*!*/ project)
        {
            Utilities.ArgumentNotNull("project", project);

            _serviceProvider = serviceProvider;
            _pyService       = pyService;
            _project         = project;
        }
コード例 #10
0
        public DefaultPythonLauncherOptions(IPythonProject properties)
        {
            _properties = properties;
            InitializeComponent();

            _debugGroup.Visible = true;
            _mixedMode.Visible  = true;
        }
コード例 #11
0
        public IProjectLauncher CreateLauncher(IPythonProject project) {
            var webLauncher = _providers.FirstOrDefault(p => p.Value.Name == PythonConstants.WebLauncherName);

            if (webLauncher == null) {
                throw new InvalidOperationException("Cannot find Python Web launcher");
            }

            return webLauncher.Value.CreateLauncher(project);
        }
コード例 #12
0
ファイル: Extensions.cs プロジェクト: rsumner33/PTVS
        public static Platform TargetPlatform(this IPythonProject project)
        {
            Platform platform;

            if (!Enum.TryParse <Platform>(project.GetProperty(ClusterOptions.TargetPlatformSetting), true, out platform))
            {
                platform = Platform.X86;
            }
            return(platform);
        }
コード例 #13
0
ファイル: Extensions.cs プロジェクト: rsumner33/PTVS
        public static bool PublishBeforeRun(this IPythonProject project)
        {
            string optValue = project.GetProperty(ClusterOptions.PublishBeforeRunSetting);
            bool   pubBeforeRun;

            if (optValue != null && Boolean.TryParse(optValue, out pubBeforeRun))
            {
                return(pubBeforeRun);
            }
            return(true);
        }
コード例 #14
0
        public IProjectLauncher CreateLauncher(IPythonProject project)
        {
            var webLauncher = _providers.FirstOrDefault(p => p.Value.Name == PythonConstants.WebLauncherName);

            if (webLauncher == null)
            {
                throw new InvalidOperationException("Cannot find Python Web launcher");
            }

            return(webLauncher.Value.CreateLauncher(project));
        }
コード例 #15
0
        internal static IEnumerable <string> EnumerateSearchPaths(IPythonProject project)
        {
            var seen = new HashSet <string>();

            var paths = project.GetProperty(PythonConstants.SearchPathSetting);

            if (!string.IsNullOrEmpty(paths))
            {
                foreach (var path in paths.Split(';'))
                {
                    if (string.IsNullOrEmpty(path))
                    {
                        continue;
                    }

                    var absPath = CommonUtils.GetAbsoluteFilePath(project.ProjectDirectory, path);
                    if (seen.Add(absPath))
                    {
                        yield return(absPath);
                    }
                }
            }

            var interp = project.GetProjectAnalyzer().Interpreter as IPythonInterpreterWithProjectReferences2;

            if (interp != null)
            {
                foreach (var r in interp.GetReferences())
                {
                    if (r.Kind == ProjectReferenceKind.ExtensionModule)
                    {
                        string absPath;
                        try {
                            absPath = CommonUtils.GetAbsoluteFilePath(project.ProjectDirectory, r.Name);
                        } catch (InvalidOperationException) {
                            continue;
                        }

                        if (!string.IsNullOrEmpty(absPath))
                        {
                            var parentPath = CommonUtils.GetParent(absPath);
                            if (!string.IsNullOrEmpty(parentPath) && seen.Add(parentPath))
                            {
                                yield return(parentPath);
                            }
                        }
                    }
                }
            }
        }
コード例 #16
0
 private async void RunInConsole(IPythonProject project, CommandStartInfo startInfo)
 {
     using (var process = ProcessOutput.Run(
                startInfo.Filename,
                new[] { startInfo.Arguments },
                startInfo.WorkingDirectory,
                startInfo.EnvironmentVariables,
                true,
                null,
                quoteArgs: false
                )) {
         await process;
     }
 }
コード例 #17
0
 public void AssertMatchesProject(IPythonProject project) {
     Assert.AreEqual(PropertyValue(project, PythonConstants.SearchPathSetting), SearchPaths, "SearchPaths does not match");
     Assert.AreEqual(PropertyValue(project, PythonConstants.CommandLineArgumentsSetting), CommandLineArguments, "CommandLineArguments does not match");
     Assert.AreEqual(PropertyValue(project, PythonConstants.InterpreterArgumentsSetting), InterpreterArguments, "InterpreterArguments does not match");
     Assert.AreEqual(PropertyValue(project, PythonConstants.InterpreterPathSetting), InterpreterPath, "InterpreterPath does not match");
     Assert.AreEqual(PropertyValue(project, PythonConstants.WebBrowserUrlSetting), WebBrowserUrl, "WebBrowserUrl does not match");
     Assert.AreEqual(PropertyValue(project, PythonConstants.WebBrowserPortSetting), WebBrowserPort, "WebBrowserPort does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.RunWebServerTargetProperty), RunWebServerTarget, "RunWebServerTarget does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.RunWebServerTargetTypeProperty, "script"), RunWebServerTargetType, "RunWebServerTargetType does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.RunWebServerArgumentsProperty), RunWebServerArguments, "RunWebServerArguments does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.RunWebServerEnvironmentProperty), RunWebServerEnvironment, "RunWebServerEnvironment does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.DebugWebServerTargetProperty), DebugWebServerTarget, "DebugWebServerTarget does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.DebugWebServerTargetTypeProperty, "script"), DebugWebServerTargetType, "DebugWebServerTargetType does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.DebugWebServerArgumentsProperty), DebugWebServerArguments, "DebugWebServerArguments does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.DebugWebServerEnvironmentProperty), DebugWebServerEnvironment, "DebugWebServerEnvironment does not match");
 }
コード例 #18
0
        private static LaunchConfiguration GetMSBuildCommandConfig(
            LaunchConfiguration original,
            IPythonProject project,
            string targetProperty,
            string targetTypeProperty,
            string argumentsProperty,
            string environmentProperty
        ) {
            var target = DoSubstitutions(original, project, project.GetProperty(targetProperty));
            if (string.IsNullOrEmpty(target)) {
                target = original.ScriptName;
            }

            var targetType = project.GetProperty(targetTypeProperty);
            if (string.IsNullOrEmpty(targetType)) {
                targetType = PythonCommandTask.TargetTypeScript;
            }

            var config = original.Clone();
            if (PythonCommandTask.TargetTypeModule.Equals(targetType, StringComparison.OrdinalIgnoreCase)) {
                if (string.IsNullOrEmpty(config.InterpreterArguments)) {
                    config.InterpreterArguments = "-m " + target;
                } else {
                    config.InterpreterArguments = config.InterpreterArguments + " -m " + target;
                }
            } else if (PythonCommandTask.TargetTypeExecutable.Equals(targetType, StringComparison.OrdinalIgnoreCase)) {
                config.InterpreterPath = target;
            } else {
                config.ScriptName = target;
            }

            var args = DoSubstitutions(original, project, project.GetProperty(argumentsProperty));
            if (!string.IsNullOrEmpty(args)) {
                if (string.IsNullOrEmpty(config.ScriptArguments)) {
                    config.ScriptArguments = args;
                } else {
                    config.ScriptArguments = config.ScriptArguments + " " + args;
                }
            }

            var env = DoSubstitutions(original, project, project.GetProperty(environmentProperty));
            config.Environment = PathUtils.MergeEnvironments(config.Environment, PathUtils.ParseEnvironment(env));

            return config;
        }
コード例 #19
0
ファイル: DebugAsScriptCommand.cs プロジェクト: xNUTs/PTVS
        public override void DoCommand(object sender, EventArgs args)
        {
            var file = CommonPackage.GetActiveTextView().GetFilePath();

            // Launch with project context if there is one and it contains the active document
            // Fallback to using default python project
            var pythonProjectNode = CommonPackage.GetStartupProject() as PythonProjectNode;

            if ((pythonProjectNode != null) && (pythonProjectNode.FindNodeByFullPath(file) == null))
            {
                pythonProjectNode = null;
            }
            IPythonProject pythonProject = pythonProjectNode as IPythonProject ?? new DefaultPythonProject(file);

            var launcher = PythonToolsPackage.GetLauncher(pythonProject);

            launcher.LaunchFile(file, true);
        }
コード例 #20
0
ファイル: PythonWebLauncher.cs プロジェクト: wenh123/PTVS
        public PythonWebLauncher(IServiceProvider serviceProvider, PythonToolsService pyService, IPythonProject project) {
            _pyService = pyService;
            _project = project;
            _serviceProvider = serviceProvider;

            var project2 = project as IPythonProject2;
            if (project2 != null) {
                // The provider may return its own object, but the web launcher only
                // supports instances of CustomCommand.
                _runServerCommand = project2.FindCommand(RunWebServerCommand);
                _debugServerCommand = project2.FindCommand(DebugWebServerCommand);
            }

            var portNumber = _project.GetProperty(PythonConstants.WebBrowserPortSetting);
            int portNum;
            if (Int32.TryParse(portNumber, out portNum)) {
                _testServerPort = portNum;
            }
        }
コード例 #21
0
        private string GetInterpreterPath(IPythonProject project, bool isWindows)
        {
            var factory = project.GetInterpreterFactory();

            if (factory == null)
            {
                throw new NoInterpretersException();
            }

            var interpreterService = _serviceProvider.GetComponentModel().GetService <IInterpreterOptionsService>();

            if (interpreterService == null || factory == interpreterService.NoInterpretersValue)
            {
                throw new NoInterpretersException();
            }

            return(isWindows ?
                   factory.Configuration.WindowsInterpreterPath :
                   factory.Configuration.InterpreterPath);
        }
コード例 #22
0
        internal static string DoSubstitutions(LaunchConfiguration original, IPythonProject project, string str) {
            if (string.IsNullOrEmpty(str)) {
                return str;
            }

            return SubstitutionPattern.Replace(
                str,
                m => {
                    switch (m.Groups[1].Value.ToLowerInvariant()) {
                        case "startupfile":
                            return original.ScriptName;
                        case "startupmodule":
                            try {
                                return ModulePath.FromFullPath(original.ScriptName, project.ProjectHome).ModuleName;
                            } catch (ArgumentException) {
                            }
                            break;
                    }
                    return m.Value;
                }
            );
        }
コード例 #23
0
        private async void RunInOutput(IPythonProject 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;
            }
        }
コード例 #24
0
        public IProjectLauncher CreateLauncher(IPythonProject project)
        {
            var defaultConfig = project.GetLaunchConfigurationOrThrow();

            var runConfig = GetMSBuildCommandConfig(
                defaultConfig,
                project,
                PythonWebLauncher.RunWebServerTargetProperty,
                PythonWebLauncher.RunWebServerTargetTypeProperty,
                PythonWebLauncher.RunWebServerArgumentsProperty,
                PythonWebLauncher.RunWebServerEnvironmentProperty
                );
            var debugConfig = GetMSBuildCommandConfig(
                defaultConfig,
                project,
                PythonWebLauncher.DebugWebServerTargetProperty,
                PythonWebLauncher.DebugWebServerTargetTypeProperty,
                PythonWebLauncher.DebugWebServerArgumentsProperty,
                PythonWebLauncher.DebugWebServerEnvironmentProperty
                );

            // Check project type GUID and enable the Django-specific features
            // of the debugger if required.
            var projectGuids = project.GetUnevaluatedProperty("ProjectTypeGuids") ?? "";

            // HACK: Literal GUID string to avoid introducing Django-specific public API
            // We don't want to expose a constant from PythonTools.dll.
            // TODO: Add generic breakpoint extension point
            // to avoid having to pass this property for Django and any future
            // extensions.
            if (projectGuids.IndexOf("5F0BE9CA-D677-4A4D-8806-6076C0FAAD37", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                debugConfig.LaunchOptions["DjangoDebug"]   = "true";
                defaultConfig.LaunchOptions["DjangoDebug"] = "true";
            }

            return(new PythonWebLauncher(_serviceProvider, runConfig, debugConfig, defaultConfig));
        }
コード例 #25
0
ファイル: PythonWebLauncher.cs プロジェクト: xNUTs/PTVS
        public PythonWebLauncher(IServiceProvider serviceProvider, PythonToolsService pyService, IPythonProject project)
        {
            _pyService       = pyService;
            _project         = project;
            _serviceProvider = serviceProvider;

            var project2 = project as IPythonProject2;

            if (project2 != null)
            {
                // The provider may return its own object, but the web launcher only
                // supports instances of CustomCommand.
                _runServerCommand   = project2.FindCommand(RunWebServerCommand);
                _debugServerCommand = project2.FindCommand(DebugWebServerCommand);
            }

            var portNumber = _project.GetProperty(PythonConstants.WebBrowserPortSetting);
            int portNum;

            if (Int32.TryParse(portNumber, out portNum))
            {
                _testServerPort = portNum;
            }
        }
コード例 #26
0
        internal static IDictionary <string, TargetResult> BuildTarget(IPythonProject project, string target)
        {
            var config = project.GetMSBuildProjectInstance();

            if (config == null)
            {
                throw new ArgumentException(Strings.ProjectDoesNotSupportedMSBuild, nameof(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);
        }
コード例 #27
0
 public IronPythonLauncherOptions(IPythonProject properties) : this()
 {
     _properties = properties;
 }
コード例 #28
0
 public IronPythonLauncherOptions(IPythonProject properties) : this() {
     _properties = properties;
 }
コード例 #29
0
        public IProjectLauncher CreateLauncher(IPythonProject project) {
            var defaultConfig = project.GetLaunchConfigurationOrThrow();

            var runConfig = GetMSBuildCommandConfig(
                defaultConfig,
                project,
                PythonWebLauncher.RunWebServerTargetProperty,
                PythonWebLauncher.RunWebServerTargetTypeProperty,
                PythonWebLauncher.RunWebServerArgumentsProperty,
                PythonWebLauncher.RunWebServerEnvironmentProperty
            );
            var debugConfig = GetMSBuildCommandConfig(
                defaultConfig,
                project,
                PythonWebLauncher.DebugWebServerTargetProperty,
                PythonWebLauncher.DebugWebServerTargetTypeProperty,
                PythonWebLauncher.DebugWebServerArgumentsProperty,
                PythonWebLauncher.DebugWebServerEnvironmentProperty
            );

            // Check project type GUID and enable the Django-specific features
            // of the debugger if required.
            var projectGuids = project.GetUnevaluatedProperty("ProjectTypeGuids") ?? "";
            // HACK: Literal GUID string to avoid introducing Django-specific public API
            // We don't want to expose a constant from PythonTools.dll.
            // TODO: Add generic breakpoint extension point
            // to avoid having to pass this property for Django and any future
            // extensions.
            if (projectGuids.IndexOf("5F0BE9CA-D677-4A4D-8806-6076C0FAAD37", StringComparison.OrdinalIgnoreCase) >= 0) {
                debugConfig.LaunchOptions["DjangoDebug"] = "true";
                defaultConfig.LaunchOptions["DjangoDebug"] = "true";
            }

            return new PythonWebLauncher(_serviceProvider, runConfig, debugConfig, defaultConfig);
        }
コード例 #30
0
        public CommandStartInfo GetStartInfo(IPythonProject project)
        {
            var outputs = BuildTarget(project, _target);
            var config  = project.GetLaunchConfigurationOrThrow();

            var item = outputs.Values
                       .SelectMany(result => result.Items)
                       .FirstOrDefault(i =>
                                       !string.IsNullOrEmpty(i.ItemSpec) &&
                                       !string.IsNullOrEmpty(i.GetMetadata(CreatePythonCommandItem.TargetTypeKey))
                                       );

            if (item == null)
            {
                throw new InvalidOperationException(Strings.ErrorBuildingCustomCommand.FormatUI(_target));
            }

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

            var pathVar = config.Interpreter.PathEnvironmentVariable;
            var env     = new Dictionary <string, string> {
                { pathVar, PathUtils.JoinPathList(config.SearchPaths) }
            };

            startInfo.EnvironmentVariables = PathUtils.MergeEnvironments(
                PathUtils.MergeEnvironments(env, config.Environment, pathVar),
                PathUtils.ParseEnvironment(item.GetMetadata(CreatePythonCommandItem.EnvironmentKey)),
                "Path", config.Interpreter.PathEnvironmentVariable
                );

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

            string errorRegex = item.GetMetadata(CreatePythonCommandItem.ErrorRegexKey);

            if (!string.IsNullOrEmpty(errorRegex))
            {
                startInfo.ErrorRegex = new Regex(errorRegex);
            }

            string warningRegex = item.GetMetadata(CreatePythonCommandItem.WarningRegexKey);

            if (!string.IsNullOrEmpty(warningRegex))
            {
                startInfo.WarningRegex = new Regex(warningRegex);
            }

            startInfo.EnvironmentVariables["PYTHONUNBUFFERED"] = "1";

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

            return(startInfo);
        }
コード例 #31
0
ファイル: HpcLauncher.cs プロジェクト: wenh123/PTVS
 public HpcLauncher(PythonToolsService pyService, IPythonProject project) {
     _pyService = pyService;
     _project = project;
 }
コード例 #32
0
ファイル: WslLauncher.cs プロジェクト: zyxws012/PTVS
 public IProjectLauncher CreateLauncher(IPythonProject project)
 {
     return(new WslPythonLauncher(_provider, project.GetLaunchConfigurationOrThrow()));
 }
コード例 #33
0
 public ClusterOptionsControl(IPythonProject project) : this()
 {
     _project = project;
     _options = new ClusterOptions(project);
 }
コード例 #34
0
        private async void RunInOutput(IPythonProject 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;
            }
        }
コード例 #35
0
 public IProjectLauncher CreateLauncher(IPythonProject project) {
     return new DefaultPythonLauncher(_serviceProvider, project.GetLaunchConfigurationOrThrow());
 }
コード例 #36
0
 private async void RunInConsole(IPythonProject project, CommandStartInfo startInfo) {
     using (var process = ProcessOutput.Run(
         startInfo.Filename,
         new[] { startInfo.Arguments },
         startInfo.WorkingDirectory,
         startInfo.EnvironmentVariables,
         true,
         null,
         quoteArgs: false
     )) {
         await process;
     }
 }
コード例 #37
0
ファイル: ClusterOptions.cs プロジェクト: wenh123/PTVS
 public ClusterOptions(IPythonProject project) {
     _project = project;            
 }
コード例 #38
0
ファイル: PythonToolsPackage.cs プロジェクト: wenh123/PTVS
        internal static IProjectLauncher GetLauncher(IServiceProvider serviceProvider, IPythonProject project) {
            var launchProvider = serviceProvider.GetUIThread().Invoke<string>(() => project.GetProperty(PythonConstants.LaunchProvider));

            IPythonLauncherProvider defaultLaunchProvider = null;
            foreach (var launcher in serviceProvider.GetComponentModel().GetExtensions<IPythonLauncherProvider>()) {
                if (launcher.Name == launchProvider) {
                    return serviceProvider.GetUIThread().Invoke<IProjectLauncher>(() => launcher.CreateLauncher(project));
                }

                if (launcher.Name == DefaultLauncherProvider.DefaultLauncherName) {
                    defaultLaunchProvider = launcher;
                }
            }

            // no launcher configured, use the default one.
            Debug.Assert(defaultLaunchProvider != null);
            return (defaultLaunchProvider != null) ?
                serviceProvider.GetUIThread().Invoke<IProjectLauncher>(() => defaultLaunchProvider.CreateLauncher(project)) :
                null;
        }
コード例 #39
0
 public void AssertMatchesProject(IPythonProject project) {
     Assert.AreEqual(PropertyValue(project, PythonConstants.SearchPathSetting), SearchPaths, "SearchPaths does not match");
     Assert.AreEqual(PropertyValue(project, PythonConstants.CommandLineArgumentsSetting), CommandLineArguments, "CommandLineArguments does not match");
     Assert.AreEqual(PropertyValue(project, PythonConstants.InterpreterArgumentsSetting), InterpreterArguments, "InterpreterArguments does not match");
     Assert.AreEqual(PropertyValue(project, PythonConstants.InterpreterPathSetting), InterpreterPath, "InterpreterPath does not match");
     Assert.AreEqual(PropertyValue(project, PythonConstants.WebBrowserUrlSetting), WebBrowserUrl, "WebBrowserUrl does not match");
     Assert.AreEqual(PropertyValue(project, PythonConstants.WebBrowserPortSetting), WebBrowserPort, "WebBrowserPort does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.RunWebServerTargetProperty), RunWebServerTarget, "RunWebServerTarget does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.RunWebServerTargetTypeProperty, "script"), RunWebServerTargetType, "RunWebServerTargetType does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.RunWebServerArgumentsProperty), RunWebServerArguments, "RunWebServerArguments does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.RunWebServerEnvironmentProperty), RunWebServerEnvironment, "RunWebServerEnvironment does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.DebugWebServerTargetProperty), DebugWebServerTarget, "DebugWebServerTarget does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.DebugWebServerTargetTypeProperty, "script"), DebugWebServerTargetType, "DebugWebServerTargetType does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.DebugWebServerArgumentsProperty), DebugWebServerArguments, "DebugWebServerArguments does not match");
     Assert.AreEqual(PropertyValue(project, PythonWebLauncher.DebugWebServerEnvironmentProperty), DebugWebServerEnvironment, "DebugWebServerEnvironment does not match");
 }
コード例 #40
0
 public IPythonLauncherOptions GetLauncherOptions(IPythonProject properties) {
     return new PythonWebLauncherOptions(properties);
 }
コード例 #41
0
        public static string GetCommandsDisplayLabel(
            Microsoft.Build.Evaluation.Project project,
            IPythonProject 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);
        }
コード例 #42
0
 public ClusterOptions(IPythonProject project)
 {
     _project = project;
 }
コード例 #43
0
        private static string PerformSubstitutions(IPythonProject 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;
            });
        }
コード例 #44
0
ファイル: ClusterOptionsControl.cs プロジェクト: wenh123/PTVS
 public ClusterOptionsControl(IPythonProject project) : this() {
     _project = project;
     _options = new ClusterOptions(project);
 }
コード例 #45
0
        internal static void AddSearchPaths(
            Dictionary<string, string> env,
            IPythonProject project,
            IServiceProvider provider = null
        ) {
            var pathEnv = project.GetProjectAnalyzer().InterpreterFactory.Configuration.PathEnvironmentVariable;
            if (string.IsNullOrEmpty(pathEnv)) {
                return;
            }

            var paths = new List<string>();
            
            string path;
            if (env.TryGetValue(pathEnv, out path)) {
                paths.AddRange(path.Split(Path.PathSeparator));
            }

            paths.AddRange(EnumerateSearchPaths(project));

            if (provider != null && !provider.GetPythonToolsService().GeneralOptions.ClearGlobalPythonPath) {
                paths.AddRange((Environment.GetEnvironmentVariable(pathEnv) ?? "")
                    .Split(Path.PathSeparator)
                    .Where(p => !paths.Contains(p))
                    .ToList());
            }

            env[pathEnv] = string.Join(
                Path.PathSeparator.ToString(),
                paths
            );
        }
コード例 #46
0
        public static IPythonProjectLaunchProperties Create(
            IPythonProject project,
            IServiceProvider site,
            IProjectLaunchProperties properties
        ) {
            var res = properties as IPythonProjectLaunchProperties;
            if (res != null) {
                return res;
            }
            
            res = project as IPythonProjectLaunchProperties;
            if (res != null) {
                // This should be the common case, as we implement
                // IPythonProjectLaunchProperties on our project.
                return res;
            }

            // Backwards compatibility shim to handle project implementations
            // that omit IPythonProjectLaunchProperties.

            string arguments, workingDir;
            Dictionary<string, string> environment, environmentWithPaths;
            properties = properties ?? (project as IProjectLaunchProperties);
            if (properties != null) {
                arguments = properties.GetArguments();
                workingDir = properties.GetWorkingDirectory();
                environment = new Dictionary<string, string>(properties.GetEnvironment(false));
                environmentWithPaths = new Dictionary<string, string>(properties.GetEnvironment(true));
            } else {
                arguments = project.GetProperty(CommonConstants.CommandLineArguments);
                workingDir = project.GetWorkingDirectory();

                environment = ParseEnvironment(project.GetProperty(PythonConstants.EnvironmentSetting));
                environmentWithPaths = new Dictionary<string, string>(environment);
                AddSearchPaths(environmentWithPaths, project, site);
            }

            string strValue;
            bool boolValue;
            bool? isWindowsApplication = null;
            strValue = project.GetProperty(PythonConstants.IsWindowsApplicationSetting);
            if (bool.TryParse(strValue, out boolValue)) {
                isWindowsApplication = boolValue;
            }

            IPythonInterpreterFactory interpreter;

            var ipp3 = project as IPythonProject3;
            if (ipp3 != null) {
                interpreter = ipp3.GetInterpreterFactoryOrThrow();
            } else {
                interpreter = project.GetInterpreterFactory();
                var service = site.GetComponentModel().GetService<IInterpreterOptionsService>();
                if (service == null || interpreter == service.NoInterpretersValue) {
                    throw new NoInterpretersException();
                }
            }

            var interpreterPath = (isWindowsApplication ?? false) ?
                interpreter.Configuration.WindowsInterpreterPath :
                interpreter.Configuration.InterpreterPath;

            var interpreterArguments = project.GetProperty(PythonConstants.InterpreterArgumentsSetting);

            bool? isNativeDebugging = null;
            strValue = project.GetProperty(PythonConstants.EnableNativeCodeDebugging);
            if (bool.TryParse(strValue, out boolValue)) {
                isNativeDebugging = boolValue;
            }

            return new PythonProjectLaunchProperties(
                arguments,
                workingDir,
                environment,
                environmentWithPaths,
                interpreterPath,
                interpreterArguments,
                isWindowsApplication,
                isNativeDebugging
            );
        }
コード例 #47
0
        private async Task <bool> RunInRepl(IPythonProject 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.GetTemporaryId(
                ReplId + executeIn.Substring(4),
                _project.GetInterpreterFactory().Configuration
                );

            var model        = _project.Site.GetComponentModel();
            var replProvider = model.GetService <InteractiveWindowProvider>();

            if (replProvider == null)
            {
                return(false);
            }

            bool created;
            var  replWindow = replProvider.OpenOrCreateTemporary(replWindowId, replTitle, out created);

            // TODO: Find alternative way of closing repl window on Dev15
            var replFrame = (replWindow as ToolWindowPane)?.Frame as IVsWindowFrame;

            var interactive = replWindow.InteractiveWindow;
            var pyEvaluator = replWindow.InteractiveWindow.Evaluator as PythonInteractiveEvaluator;

            if (pyEvaluator == 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);
            }

            pyEvaluator.ProjectMoniker = _project.GetMkDocument();
            pyEvaluator.Configuration  = new LaunchConfiguration(startInfo.Interpreter)
            {
                WorkingDirectory = startInfo.WorkingDirectory,
                Environment      = startInfo.EnvironmentVariables.ToDictionary(kv => kv.Key, kv => kv.Value)
            };

            project.AddActionOnClose((object)replWindow, InteractiveWindowProvider.Close);

            replWindow.Show(true);

            var result = await pyEvaluator.ResetAsync(false, quiet : true);

            if (result.IsSuccessful)
            {
                try {
                    var filename  = startInfo.Filename;
                    var arguments = startInfo.Arguments ?? string.Empty;

                    if (startInfo.IsScript)
                    {
                        interactive.WriteLine(Strings.CustomCommandExecutingScript.FormatUI(Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteFileAsync(filename, arguments);
                    }
                    else if (startInfo.IsModule)
                    {
                        interactive.WriteLine(Strings.CustomCommandExecutingModule.FormatUI(filename, arguments));
                        Debug.WriteLine("Executing -m {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteModuleAsync(filename, arguments);
                    }
                    else if (startInfo.IsCode)
                    {
                        Debug.WriteLine("Executing -c \"{0}\"", filename, arguments);
                        await pyEvaluator.ExecuteCodeAsync(filename);
                    }
                    else
                    {
                        interactive.WriteLine(Strings.CustomCommandExecutingOther.FormatUI(Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteProcessAsync(filename, arguments);
                    }

                    if (resetRepl)
                    {
                        // We really close the backend, rather than resetting.
                        pyEvaluator.Dispose();
                    }
                } 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);
        }
コード例 #48
0
ファイル: HpcLauncherProvider.cs プロジェクト: wenh123/PTVS
 public IProjectLauncher CreateLauncher(IPythonProject project) {
     return new HpcLauncher(_pyService, project);
 }
コード例 #49
0
        private async Task<bool> RunInRepl(IPythonProject 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.GetTemporaryId(
                ReplId + executeIn.Substring(4),
                _project.GetInterpreterFactory().Configuration
            );
            
            var model = _project.Site.GetComponentModel();
            var replProvider = model.GetService<InteractiveWindowProvider>();
            if (replProvider == null) {
                return false;
            }

            bool created;
            var replWindow = replProvider.OpenOrCreateTemporary(replWindowId, replTitle, out created);

            // TODO: Find alternative way of closing repl window on Dev15
            var replFrame = (replWindow as ToolWindowPane)?.Frame as IVsWindowFrame;

            var interactive = replWindow.InteractiveWindow;
            var pyEvaluator = replWindow.InteractiveWindow.Evaluator as PythonInteractiveEvaluator;
            if (pyEvaluator == 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);
            }

            pyEvaluator.ProjectMoniker = _project.GetMkDocument();
            pyEvaluator.Configuration = new LaunchConfiguration(startInfo.Interpreter) {
                WorkingDirectory = startInfo.WorkingDirectory,
                Environment = startInfo.EnvironmentVariables.ToDictionary(kv => kv.Key, kv => kv.Value)
            };

            project.AddActionOnClose((object)replWindow, InteractiveWindowProvider.Close);

            replWindow.Show(true);

            var result = await pyEvaluator.ResetAsync(false, quiet: true);

            if (result.IsSuccessful) {
                try {
                    var filename = startInfo.Filename;
                    var arguments = startInfo.Arguments ?? string.Empty;

                    if (startInfo.IsScript) {
                        interactive.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteFileAsync(filename, arguments);
                    } else if (startInfo.IsModule) {
                        interactive.WriteLine(string.Format("Executing -m {0} {1}", filename, arguments));
                        Debug.WriteLine("Executing -m {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteModuleAsync(filename, arguments);
                    } else if (startInfo.IsCode) {
                        Debug.WriteLine("Executing -c \"{0}\"", filename, arguments);
                        await pyEvaluator.ExecuteCodeAsync(filename);
                    } else {
                        interactive.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteProcessAsync(filename, arguments);
                    }

                    if (resetRepl) {
                        // We really close the backend, rather than resetting.
                        pyEvaluator.Dispose();
                    }
                } 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;
        }
コード例 #50
0
 private static string PropertyValue(IPythonProject project, string property, string defaultValue = "") {
     return ((PythonProjectNode)project).Site.GetUIThread().Invoke(() => project.GetUnevaluatedProperty(property) ?? defaultValue);
 }
コード例 #51
0
ファイル: IronPythonLauncher.cs プロジェクト: wenh123/PTVS
 public IronPythonLauncher(IServiceProvider serviceProvider, PythonToolsService pyService, IPythonProject project) {
     _serviceProvider = serviceProvider;
     _pyService = pyService;
     _project = project;
 }
コード例 #52
0
 public IProjectLauncher CreateLauncher(IPythonProject project) {
     return new DefaultPythonLauncher(_serviceProvider, _pyService, project);
 }
コード例 #53
0
 public IPythonLauncherOptions GetLauncherOptions(IPythonProject properties)
 {
     return(new PythonWebLauncherOptions(properties));
 }
コード例 #54
0
        public CommandStartInfo GetStartInfo(IPythonProject project) {
            var outputs = BuildTarget(project, _target);
            var config = project.GetLaunchConfigurationOrThrow();

            var item = outputs.Values
                .SelectMany(result => result.Items)
                .FirstOrDefault(i =>
                    !string.IsNullOrEmpty(i.ItemSpec) &&
                    !string.IsNullOrEmpty(i.GetMetadata(CreatePythonCommandItem.TargetTypeKey))
                );

            if (item == null) {
                throw new InvalidOperationException(Strings.ErrorBuildingCustomCommand.FormatUI(_target));
            }

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

            var pathVar = config.Interpreter.PathEnvironmentVariable;
            var env = new Dictionary<string, string> {
                { pathVar, PathUtils.JoinPathList(config.SearchPaths) }
            };
            startInfo.EnvironmentVariables = PathUtils.MergeEnvironments(
                PathUtils.MergeEnvironments(env, config.Environment, pathVar),
                PathUtils.ParseEnvironment(item.GetMetadata(CreatePythonCommandItem.EnvironmentKey)),
                "Path", config.Interpreter.PathEnvironmentVariable
            );

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

            string errorRegex = item.GetMetadata(CreatePythonCommandItem.ErrorRegexKey);
            if (!string.IsNullOrEmpty(errorRegex)) {
                startInfo.ErrorRegex = new Regex(errorRegex);
            }

            string warningRegex = item.GetMetadata(CreatePythonCommandItem.WarningRegexKey);
            if (!string.IsNullOrEmpty(warningRegex)) {
                startInfo.WarningRegex = new Regex(warningRegex);
            }

            startInfo.EnvironmentVariables["PYTHONUNBUFFERED"] = "1";

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

            return startInfo;
        }
コード例 #55
0
ファイル: IronPythonLauncher.cs プロジェクト: xyongy/PTVS
 public IronPythonLauncher(IServiceProvider serviceProvider, PythonToolsService pyService, IPythonProject project)
 {
     _serviceProvider = serviceProvider;
     _pyService       = pyService;
     _project         = project;
 }
コード例 #56
0
        internal static IDictionary<string, TargetResult> BuildTarget(IPythonProject 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;
        }
コード例 #57
0
        internal static IEnumerable<string> EnumerateSearchPaths(IPythonProject project) {
            var seen = new HashSet<string>();

            var paths = project.GetProperty(PythonConstants.SearchPathSetting);
            if (!string.IsNullOrEmpty(paths)) {
                foreach (var path in paths.Split(';')) {
                    if (string.IsNullOrEmpty(path)) {
                        continue;
                    }

                    var absPath = CommonUtils.GetAbsoluteFilePath(project.ProjectDirectory, path);
                    if (seen.Add(absPath)) {
                        yield return absPath;
                    }
                }
            }

            var interp = project.GetProjectAnalyzer().Interpreter as IPythonInterpreterWithProjectReferences2;
            if (interp != null) {
                foreach (var r in interp.GetReferences()) {
                    if (r.Kind == ProjectReferenceKind.ExtensionModule) {
                        string absPath;
                        try {
                            absPath = CommonUtils.GetAbsoluteFilePath(project.ProjectDirectory, r.Name);
                        } catch (InvalidOperationException) {
                            continue;
                        }

                        if (!string.IsNullOrEmpty(absPath)) {
                            var parentPath = CommonUtils.GetParent(absPath);
                            if (!string.IsNullOrEmpty(parentPath) && seen.Add(parentPath)) {
                                yield return parentPath;
                            }
                        }
                    }
                }
            }
        }
コード例 #58
0
        private static LaunchConfiguration GetMSBuildCommandConfig(
            LaunchConfiguration original,
            IPythonProject project,
            string targetProperty,
            string targetTypeProperty,
            string argumentsProperty,
            string environmentProperty
            )
        {
            var target = DoSubstitutions(original, project, project.GetProperty(targetProperty));

            if (string.IsNullOrEmpty(target))
            {
                target = original.ScriptName;
            }

            var targetType = project.GetProperty(targetTypeProperty);

            if (string.IsNullOrEmpty(targetType))
            {
                targetType = PythonCommandTask.TargetTypeScript;
            }

            var config = original.Clone();

            if (PythonCommandTask.TargetTypeModule.Equals(targetType, StringComparison.OrdinalIgnoreCase))
            {
                if (string.IsNullOrEmpty(config.InterpreterArguments))
                {
                    config.InterpreterArguments = "-m " + target;
                }
                else
                {
                    config.InterpreterArguments = config.InterpreterArguments + " -m " + target;
                }
            }
            else if (PythonCommandTask.TargetTypeExecutable.Equals(targetType, StringComparison.OrdinalIgnoreCase))
            {
                config.InterpreterPath = target;
            }
            else
            {
                config.ScriptName = target;
            }

            var args = DoSubstitutions(original, project, project.GetProperty(argumentsProperty));

            if (!string.IsNullOrEmpty(args))
            {
                if (string.IsNullOrEmpty(config.ScriptArguments))
                {
                    config.ScriptArguments = args;
                }
                else
                {
                    config.ScriptArguments = config.ScriptArguments + " " + args;
                }
            }

            var env = DoSubstitutions(original, project, project.GetProperty(environmentProperty));

            config.Environment = PathUtils.MergeEnvironments(config.Environment, PathUtils.ParseEnvironment(env));

            return(config);
        }
コード例 #59
0
ファイル: PythonToolsPackage.cs プロジェクト: serg32m/PTVS
        internal static IProjectLauncher GetLauncher(IServiceProvider serviceProvider, IPythonProject project)
        {
            var launchProvider = serviceProvider.GetUIThread().Invoke <string>(() => project.GetProperty(PythonConstants.LaunchProvider));

            IPythonLauncherProvider defaultLaunchProvider = null;

            foreach (var launcher in serviceProvider.GetComponentModel().GetExtensions <IPythonLauncherProvider>())
            {
                if (launcher.Name == launchProvider)
                {
                    return(serviceProvider.GetUIThread().Invoke <IProjectLauncher>(() => launcher.CreateLauncher(project)));
                }

                if (launcher.Name == DefaultLauncherProvider.DefaultLauncherName)
                {
                    defaultLaunchProvider = launcher;
                }
            }

            // no launcher configured, use the default one.
            Debug.Assert(defaultLaunchProvider != null);
            return((defaultLaunchProvider != null) ?
                   serviceProvider.GetUIThread().Invoke <IProjectLauncher>(() => defaultLaunchProvider.CreateLauncher(project)) :
                   null);
        }
コード例 #60
0
ファイル: HpcLauncherProvider.cs プロジェクト: wenh123/PTVS
 public IPythonLauncherOptions GetLauncherOptions(IPythonProject properties) {
     return new ClusterOptionsControl(properties);
 }