示例#1
0
        private async Task <ProcessOutputResult> RunPythonScript(string interpreterPath, string script, string parameters, bool showWindow = false)
        {
            ProcessOutput output    = null;
            var           arguments = string.Format("\"{0}\" {1}", script, parameters);

            if (showWindow)
            {
                output = ProcessOutput.RunVisible(interpreterPath, arguments);
            }
            else
            {
                output = ProcessOutput.RunHiddenAndCapture(interpreterPath, arguments);
            }

            using (output) {
                await output;

                var r = new ProcessOutputResult()
                {
                    ExeFileName         = interpreterPath,
                    ExitCode            = output.ExitCode,
                    StandardOutputLines = output.StandardOutputLines.ToArray(),
                    StandardErrorLines  = output.StandardErrorLines.ToArray(),
                };

                // All our python scripts will return 0 if successful
                if (r.ExitCode != 0)
                {
                    throw new ProcessException(r);
                }

                return(r);
            }
        }
示例#2
0
        public void WatchWorkspaceVirtualEnvCreated()
        {
            var python = PythonPaths.Python37_x64 ?? PythonPaths.Python37;

            var workspaceFolder = TestData.GetTempPath();

            Directory.CreateDirectory(workspaceFolder);
            File.WriteAllText(Path.Combine(workspaceFolder, "app.py"), string.Empty);

            string envFolder = Path.Combine(workspaceFolder, "env");

            var workspace        = new MockWorkspace(workspaceFolder);
            var workspaceService = new MockWorkspaceService(workspace);

            // Create virtual env inside the workspace folder (one level from root)
            Action triggerDiscovery = () => {
                using (var p = ProcessOutput.RunHiddenAndCapture(python.InterpreterPath, "-m", "venv", envFolder)) {
                    Console.WriteLine(p.Arguments);
                    p.Wait();
                    Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines)));
                    Assert.AreEqual(0, p.ExitCode);
                }
            };

            var configs = TestTriggerDiscovery(workspaceService, triggerDiscovery).ToArray();

            Assert.AreEqual(1, configs.Length);
            Assert.IsTrue(PathUtils.IsSamePath(
                              Path.Combine(envFolder, "scripts", "python.exe"),
                              configs[0].InterpreterPath
                              ));
            Assert.AreEqual("Workspace|Workspace|env", configs[0].Id);
        }
示例#3
0
        protected virtual async Task <string> RunToolAsync(string interpreterExePath, string documentFilePath, Range range, string[] extraArgs)
        {
            var output = ProcessOutput.RunHiddenAndCapture(
                interpreterExePath,
                GetToolCommandArgs(documentFilePath, range, extraArgs)
                );

            await output;

            if (output.StandardErrorLines.Any(e => e.Contains("No module named")))
            {
                throw new PythonFormatterModuleNotFoundException(
                          string.Join(Environment.NewLine, output.StandardErrorLines)
                          );
            }

            if (output.StandardErrorLines.Any(e => e.Contains("ImportError")))
            {
                throw new ApplicationException(
                          string.Join(Environment.NewLine, output.StandardErrorLines)
                          );
            }

            if (output.ExitCode < 0)
            {
                throw new ApplicationException(
                          string.Join(Environment.NewLine, output.StandardErrorLines)
                          );
            }

            return(string.Join("\n", output.StandardOutputLines));
        }
示例#4
0
        private static async Task <ProcessOutputResult> RunCheckScript(string interpreterPath)
        {
            var scriptPath = PythonToolsInstallPath.GetFile("cookiecutter_check.py");
            var output     = ProcessOutput.RunHiddenAndCapture(interpreterPath, scriptPath);

            return(await WaitForOutput(interpreterPath, output));
        }
示例#5
0
 private static void CreateVirtualEnvironment(PythonVersion pythonVersion, string envPath) {
     using (var output = ProcessOutput.RunHiddenAndCapture(pythonVersion.Configuration.InterpreterPath, "-m", "venv", envPath)) {
         Assert.IsTrue(output.Wait(TimeSpan.FromMinutes(3)));
         Assert.AreEqual(0, output.ExitCode);
         Assert.IsTrue(File.Exists(Path.Combine(envPath, "Scripts", "python.exe")));
     }
 }
示例#6
0
        public async Task InstallPackage()
        {
            // Install the package into the virtual environment
            var output = ProcessOutput.RunHiddenAndCapture(_envInterpreterPath, "-m", "pip", "install", "cookiecutter<1.5");

            await WaitForOutput(_envInterpreterPath, output);
        }
示例#7
0
        // If the global interpreter comes from the Microsoft Store, and you try to create a venv
        // under %localappdata%, the venv will actually be created under the python install localcache,
        // and a redirect will be put in place that is only understood by the python.exe used to create
        // the venv.
        // Therefore, we have to use the python intepreter to check the real path of the venv,
        // in case it's been redirected.
        private async Task <string> GetRealPath(string path)
        {
            // if we can see the path, it hasn't been redirected, so no need to call into python
            if (Directory.Exists(path) || File.Exists(path))
            {
                return(path);
            }

            // get the redirected path from python
            _redirector.WriteLine(Strings.LookingForRedirectedEnv.FormatUI(path));
            var command = $"import os; print(os.path.realpath(r\"{ path }\"))";
            var output  = ProcessOutput.RunHiddenAndCapture(
                _interpreter.InterpreterExecutablePath,
                new[] { "-c", command }
                );

            try {
                var result = await WaitForOutput(_interpreter.InterpreterExecutablePath, output);

                var redirectedPath = result.StandardOutputLines.FirstOrDefault();
                if (!string.IsNullOrEmpty(redirectedPath) && Directory.Exists(redirectedPath))
                {
                    _redirector.WriteLine(Strings.LookingForRedirectedEnvFound.FormatUI(redirectedPath));
                }
                return(redirectedPath);
            } catch (ProcessException p) {
                _redirector.WriteLine(Strings.LookingForRedirectedEnvFailed.FormatUI(path));
                foreach (var line in p.Result.StandardErrorLines)
                {
                    _redirector.WriteLine(line);
                }
                throw;
            }
        }
示例#8
0
        /// <summary>
        /// Activate the specified conda environment, capture and return its environment variables.
        /// </summary>
        /// <param name="condaPath">Path to the root conda environment's conda.exe</param>
        /// <param name="prefixPath">Path to the conda environment to activate, or <c>null</c> to activate the root environment.</param>
        /// <returns>List of environment variables.</returns>
        /// <remarks>Result is cached, it is safe to call multiple times.</remarks>
        internal async static Task <IEnumerable <KeyValuePair <string, string> > > GetActivationEnvironmentVariablesForPrefixAsync(string condaPath, string prefixPath)
        {
            using (await _activationCacheLock.LockAsync(CancellationToken.None)) {
                var condaKey = new CondaCacheKey(condaPath, prefixPath);

                if (!_activationCache.TryGetValue(condaKey, out KeyValuePair <string, string>[] activationVariables))
                {
                    activationVariables = null;

                    var activateBat = Path.Combine(Path.GetDirectoryName(condaPath), "activate.bat");
                    if (File.Exists(activateBat))
                    {
                        var args = prefixPath != null
                            ? new[] { prefixPath, "&", "python.exe", "-c", PrintEnvironmentCode }
                            : new[] { "&", "python.exe", "-c", PrintEnvironmentCode };

                        using (var proc = ProcessOutput.RunHiddenAndCapture(activateBat, args)) {
                            await proc;
                            if (proc.ExitCode == 0)
                            {
                                activationVariables = ParseEnvironmentVariables(proc).ToArray();
                            }
                        }
                    }


                    _activationCache[condaKey] = activationVariables ?? new KeyValuePair <string, string> [0];
                }

                return(activationVariables);
            }
        }
        private async Task <CondaCreateDryRunResult> DoPreviewOperationAsync(IEnumerable <string> args, CancellationToken ct)
        {
            using (var output = ProcessOutput.RunHiddenAndCapture(CondaPath, args.ToArray())) {
                if (!output.IsStarted)
                {
                    return(null);
                }

                // It is safe to kill a conda dry run
                var exitCode = await WaitAndKillOnCancelAsync(output, ct);

                if (exitCode >= 0)
                {
                    var json = string.Join(Environment.NewLine, output.StandardOutputLines);
                    try {
                        return(JsonConvert.DeserializeObject <CondaCreateDryRunResult>(json));
                    } catch (JsonException ex) {
                        Debug.WriteLine("Failed to parse: {0}".FormatInvariant(ex.Message));
                        Debug.WriteLine(json);
                        return(null);
                    }
                }
            }

            return(null);
        }
        internal async Task CheckPipInstalledAsync()
        {
            if (!CanExecute)
            {
                // Don't cache the result in case our configuration gets fixed
                IsPipInstalled = false;
                return;
            }

            if (!_isPipInstalled.HasValue)
            {
                try {
                    using (var output = ProcessOutput.RunHiddenAndCapture(
                               _factory.Configuration.InterpreterPath,
                               "-E", "-c", "import pip"
                               )) {
                        IsPipInstalled = (await output) == 0;
                    }
                } catch (IOException) {
                    IsPipInstalled = false;
                } catch (OperationCanceledException) {
                    IsPipInstalled = false;
                }
            }
        }
示例#11
0
        internal async Task <IList <PipPackageView> > GetInstalledPackagesAsync()
        {
            string[] args;

            if (_factory.Configuration.Version < SupportsDashMPip)
            {
                args = new [] { "-c", "import pip; pip.main()", "list", "--no-index" };
            }
            else
            {
                args = new [] { "-m", "pip", "list", "--no-index" };
            }

            PipPackageView[] packages;

            using (var output = ProcessOutput.RunHiddenAndCapture(_factory.Configuration.InterpreterPath, args)) {
                if ((await output) != 0)
                {
                    throw new PipException(Resources.ListFailed);
                }

                packages = output.StandardOutputLines
                           .Select(s => new PipPackageView(_cache, s))
                           .ToArray();
            }

            return(packages);
        }
示例#12
0
        public void RunInterpreterOutput()
        {
            foreach (var fact in Factories)
            {
                using (var output = ProcessOutput.RunHiddenAndCapture(fact.Configuration.InterpreterPath, "-c", "import sys; print(sys.version)"))
                {
                    Assert.IsTrue(output.Wait(TimeSpan.FromSeconds(30)), "Running " + fact.Configuration.Description + " exceeded timeout");

                    foreach (var line in output.StandardOutputLines)
                    {
                        Console.WriteLine(line);
                    }
                    Console.WriteLine("END OF STDOUT");

                    foreach (var line in output.StandardErrorLines)
                    {
                        Console.WriteLine(line);
                    }
                    Console.WriteLine("END OF STDERR");

                    Assert.AreEqual(0, output.StandardErrorLines.Count());
                    Assert.AreEqual(1, output.StandardOutputLines.Count());
                }
            }
        }
示例#13
0
        private void StartPerfMon(string filename)
        {
            string perfToolsPath = GetPerfToolsPath();

            string perfMonPath = Path.Combine(perfToolsPath, "VSPerfMon.exe");

            if (!File.Exists(perfMonPath))
            {
                throw new InvalidOperationException(Strings.CannotLocatePerformanceTools);
            }

            var psi = new ProcessStartInfo(perfMonPath, "/trace /output:" + ProcessOutput.QuoteSingleArgument(filename));

            psi.CreateNoWindow         = true;
            psi.UseShellExecute        = false;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            Process.Start(psi).Dispose();

            string perfCmdPath = Path.Combine(perfToolsPath, "VSPerfCmd.exe");

            using (var p = ProcessOutput.RunHiddenAndCapture(perfCmdPath, "/waitstart")) {
                p.Wait();
                if (p.ExitCode != 0)
                {
                    throw new InvalidOperationException(Strings.StartPerfCmdError.FormatUI(
                                                            string.Join(Environment.NewLine, p.StandardOutputLines),
                                                            string.Join(Environment.NewLine, p.StandardErrorLines)
                                                            ));
                }
            }
        }
示例#14
0
        public async Task CreateCookiecutterEnv()
        {
            // Create a virtual environment using the global interpreter
            var interpreterPath = _interpreter.InterpreterExecutablePath;
            var output          = ProcessOutput.RunHiddenAndCapture(interpreterPath, "-m", "venv", _envFolderPath);

            await WaitForOutput(interpreterPath, output);
        }
        private static PythonInterpreterInformation CreateEnvironmentInfo(string prefixPath)
        {
            var name                   = Path.GetFileName(prefixPath);
            var description            = name;
            var vendor                 = Strings.CondaEnvironmentDescription;
            var vendorUrl              = string.Empty;
            var supportUrl             = string.Empty;
            var interpreterPath        = Path.Combine(prefixPath, CondaEnvironmentFactoryConstants.ConsoleExecutable);
            var windowsInterpreterPath = Path.Combine(prefixPath, CondaEnvironmentFactoryConstants.WindowsExecutable);

            InterpreterArchitecture arch = InterpreterArchitecture.Unknown;
            Version version = null;

            if (File.Exists(interpreterPath))
            {
                using (var output = ProcessOutput.RunHiddenAndCapture(
                           interpreterPath, "-c", "import sys; print('%s.%s' % (sys.version_info[0], sys.version_info[1]))"
                           )) {
                    output.Wait();
                    if (output.ExitCode == 0)
                    {
                        var versionName = output.StandardOutputLines.FirstOrDefault() ?? "";
                        if (!Version.TryParse(versionName, out version))
                        {
                            version = null;
                        }
                    }
                }

                arch = CPythonInterpreterFactoryProvider.ArchitectureFromExe(interpreterPath);
            }
            else
            {
                return(null);
            }

            var config = new InterpreterConfiguration(
                CondaEnvironmentFactoryConstants.GetInterpreterId(CondaEnvironmentFactoryProvider.EnvironmentCompanyName, name),
                description,
                prefixPath,
                interpreterPath,
                windowsInterpreterPath,
                CondaEnvironmentFactoryConstants.PathEnvironmentVariableName,
                arch,
                version
                );

            config.SwitchToFullDescription();

            var unique = new PythonInterpreterInformation(
                config,
                vendor,
                vendorUrl,
                supportUrl
                );

            return(unique);
        }
        private async Task <AddExistingEnvironmentView> AutoDetectAsync(AddExistingEnvironmentView view)
        {
            if (!Directory.Exists(view.PrefixPath))
            {
                // If view.PrefixPath is not valid by this point, we can't find anything
                // else, so abort without changes.
                return(view);
            }

            if (string.IsNullOrEmpty(view.Description))
            {
                view.Description = PathUtils.GetFileOrDirectoryName(view.PrefixPath);
            }

            if (!File.Exists(view.InterpreterPath))
            {
                view.InterpreterPath = PathUtils.FindFile(
                    view.PrefixPath,
                    CPythonInterpreterFactoryConstants.ConsoleExecutable,
                    firstCheck: new[] { "scripts" }
                    );
            }

            if (!File.Exists(view.WindowsInterpreterPath))
            {
                view.WindowsInterpreterPath = PathUtils.FindFile(
                    view.PrefixPath,
                    CPythonInterpreterFactoryConstants.WindowsExecutable,
                    firstCheck: new[] { "scripts" }
                    );
            }

            if (File.Exists(view.InterpreterPath))
            {
                using (var output = ProcessOutput.RunHiddenAndCapture(
                           view.InterpreterPath, "-c", "import sys; print('%s.%s' % (sys.version_info[0], sys.version_info[1])); print(sys.platform)"
                           )) {
                    var exitCode = await output;
                    if (exitCode == 0)
                    {
                        view.VersionName = output.StandardOutputLines.FirstOrDefault() ?? view.VersionName;
                    }
                }

                var arch = CPythonInterpreterFactoryProvider.ArchitectureFromExe(view.InterpreterPath);
                if (arch != InterpreterArchitecture.Unknown)
                {
                    view.ArchitectureName = arch.ToString();
                }

                if (string.IsNullOrEmpty(view.PathEnvironmentVariable))
                {
                    view.PathEnvironmentVariable = "PYTHONPATH";
                }
            }

            return(view);
        }
示例#17
0
        private MockInterpreterOptionsService MakeEmptyVEnv()
        {
            var python = PythonPaths.Versions.FirstOrDefault(p =>
                                                             p.IsCPython && Directory.Exists(Path.Combine(p.LibPath, "venv"))
                                                             );

            if (python == null)
            {
                Assert.Inconclusive("Requires Python with venv");
            }

            var env = TestData.GetTempPath(randomSubPath: true);

            if (env.Length > 140)
            {
                env = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                DeleteFolder.Add(env);
            }
            using (var proc = ProcessOutput.RunHiddenAndCapture(
                       python.InterpreterPath, "-m", "venv", env, "--clear"
                       )) {
                Console.WriteLine(proc.Arguments);
                proc.Wait();
                foreach (var line in proc.StandardOutputLines.Concat(proc.StandardErrorLines))
                {
                    Console.WriteLine(line);
                }
                Assert.AreEqual(0, proc.ExitCode ?? -1, "Failed to create venv");
            }

            // Forcibly remove pip so we can reinstall it
            foreach (var dir in Directory.EnumerateDirectories(Path.Combine(env, "lib", "site-packages")))
            {
                Directory.Delete(dir, true);
            }

            var service  = new MockInterpreterOptionsService();
            var provider = new MockPythonInterpreterFactoryProvider("VEnv Provider");

            provider.AddFactory(new MockPythonInterpreterFactory(
                                    new InterpreterConfiguration(
                                        "Mock;" + Guid.NewGuid().ToString(),
                                        Path.GetFileName(PathUtils.TrimEndSeparator(env)),
                                        env,
                                        PathUtils.FindFile(env, "python.exe"),
                                        PathUtils.FindFile(env, "python.exe"),
                                        Path.GetDirectoryName(PathUtils.FindFile(env, "site.py", 3)),
                                        "PYTHONPATH",
                                        python.Isx64 ? ProcessorArchitecture.Amd64 : ProcessorArchitecture.X86,
                                        python.Version.ToVersion()
                                        )
                                    ));
            service.AddProvider(provider);
            return(service);
        }
示例#18
0
 private static void EnsureDjango(string python)
 {
     using (var proc = ProcessOutput.RunHiddenAndCapture(python, "-c", "import django")) {
         proc.Wait();
         if (proc.ExitCode != 0)
         {
             DumpOutput(proc);
             Assert.Inconclusive("Django must be installed into {0} for this test", python);
         }
     }
 }
示例#19
0
        internal async Task <bool> IsPipInstalled()
        {
            AbortOnInvalidConfiguration();

            using (var output = ProcessOutput.RunHiddenAndCapture(
                       _factory.Configuration.InterpreterPath,
                       "-E", "-c", "import pip"
                       )) {
                return((await output) == 0);
            }
        }
示例#20
0
 private static void CreatePythonVirtualEnv(string pythonInterpreterPath, string workspacePath, string envName)
 {
     //Creating virtual environment and confirming it was created
     using (var p = ProcessOutput.RunHiddenAndCapture(pythonInterpreterPath, "-m", "venv", Path.Combine(workspacePath, envName))) {
         Console.WriteLine(p.Arguments);
         Assert.IsTrue(p.Wait(TimeSpan.FromMinutes(3)));
         Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines)));
         Assert.AreEqual(0, p.ExitCode);
     }
     Assert.IsTrue(File.Exists(Path.Combine(workspacePath, envName, "scripts", "python.exe")));
 }
示例#21
0
        public static void ConfigureIIS(string appCmd, string appHostConfig, string python, string wfastcgi, Dictionary <string, string> envVars)
        {
            using (var p = ProcessOutput.RunHiddenAndCapture(
                       appCmd, "set", "config", "/section:system.webServer/fastCGI",
                       string.Format("/+[fullPath='{0}', arguments='\"{1}\"']", python, wfastcgi),
                       "/AppHostConfig:" + appHostConfig
                       )) {
                p.Wait();
                DumpOutput(p);
                Assert.AreEqual(0, p.ExitCode);
            }

            using (var p = ProcessOutput.RunHiddenAndCapture(
                       appCmd, "set", "config", "/section:system.webServer/handlers",
                       string.Format(
                           "/+[name='Python_via_FastCGI',path='*',verb='*',modules='FastCgiModule',scriptProcessor='{0}|\"{1}\"',resourceType='Unspecified']",
                           python, wfastcgi
                           ),
                       "/AppHostConfig:" + appHostConfig
                       )) {
                p.Wait();
                DumpOutput(p);
                Assert.AreEqual(0, p.ExitCode);
            }

            foreach (var keyValue in envVars)
            {
                using (var p = ProcessOutput.RunHiddenAndCapture(
                           appCmd, "set", "config", "/section:system.webServer/fastCgi",
                           string.Format(
                               "/+[fullPath='{0}', arguments='\"{1}\"'].environmentVariables.[name='{2}',value='{3}']",
                               python, wfastcgi, keyValue.Key, keyValue.Value
                               ),
                           "/commit:apphost",
                           "/AppHostConfig:" + appHostConfig
                           )) {
                    p.Wait();
                    DumpOutput(p);
                    Assert.AreEqual(0, p.ExitCode);
                }
            }

            using (var p = ProcessOutput.RunHiddenAndCapture(
                       appCmd, "add", "site", "/name:TestSite",
                       "/bindings:http://localhost:8181",
                       "/physicalPath:" + Path.GetDirectoryName(appHostConfig),
                       "/AppHostConfig:" + appHostConfig
                       )) {
                p.Wait();
                DumpOutput(p);
                Assert.AreEqual(0, p.ExitCode);
            }
        }
示例#22
0
        /// <summary>
        /// Creates a Python virtual environment in specified directory.
        /// </summary>
        public static void CreateVirtualEnv(this PythonVersion pyVersion, string envPath)
        {
            var virtualEnvModule = (pyVersion.Version < PythonLanguageVersion.V30) ? "virtualenv" : "venv";

            using (var p = ProcessOutput.RunHiddenAndCapture(pyVersion.InterpreterPath, "-m", virtualEnvModule, envPath)) {
                Console.WriteLine(p.Arguments);
                Assert.IsTrue(p.Wait(TimeSpan.FromMinutes(3)));
                Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines)));
                Assert.AreEqual(0, p.ExitCode);
            }

            Assert.IsTrue(File.Exists(Path.Combine(envPath, "scripts", "python.exe")));
        }
示例#23
0
        /// <summary>
        /// Creates a Python virtual environment in vEnvPath directory and installs the specified packages
        /// </summary>
        /// <param name="pyVersion"></param>
        /// <param name="virtualEnvPath"></param>
        /// <param name="packages"></param>
        public static void CreatePythonVirtualEnvWithPkgs(this PythonVersion pyVersion, string virtualEnvPath, string[] packages)
        {
            pyVersion.CreatePythonVirtualEnv(virtualEnvPath);

            var envPythonExePath = Path.Combine(virtualEnvPath, "scripts", "python.exe");

            foreach (var package in packages.MaybeEnumerate())
            {
                using (var output = ProcessOutput.RunHiddenAndCapture(envPythonExePath, "-m", "pip", "install", package)) {
                    Assert.IsTrue(output.Wait(TimeSpan.FromSeconds(30)));
                    Assert.AreEqual(0, output.ExitCode);
                }
            }
        }
示例#24
0
        private static void CreateVirtualEnvironmentWithPackages(PythonVersion baseEnv, string envFolderPath, string[] packages)
        {
            EnvironmentUITests.CreateVirtualEnvironment(baseEnv, envFolderPath);

            var envPythonExePath = Path.Combine(envFolderPath, "scripts", "python.exe");

            foreach (var package in packages.MaybeEnumerate())
            {
                using (var output = ProcessOutput.RunHiddenAndCapture(envPythonExePath, "-m", "pip", "install", package)) {
                    Assert.IsTrue(output.Wait(TimeSpan.FromSeconds(30)));
                    Assert.AreEqual(0, output.ExitCode);
                }
            }
        }
示例#25
0
        /// <summary>
        /// Creates a Python virtual environment in specified directory and installs the specified packages.
        /// </summary>
        public static string CreateVirtualEnv(this PythonVersion pyVersion, VirtualEnvName envName, IEnumerable <string> packages, string rootDirectory = null)
        {
            var envPath          = pyVersion.CreateVirtualEnv(envName, rootDirectory);
            var envPythonExePath = Path.Combine(envPath, "scripts", "python.exe");

            foreach (var package in packages.MaybeEnumerate())
            {
                using (var output = ProcessOutput.RunHiddenAndCapture(envPythonExePath, "-m", "pip", "install", package)) {
                    Assert.IsTrue(output.Wait(TimeSpan.FromSeconds(30)));
                    Assert.AreEqual(0, output.ExitCode);
                }
            }
            return(envPath);
        }
示例#26
0
        public void TestPthFiles()
        {
            var outputPath = TestData.GetTempPath();

            Console.WriteLine("Writing to: " + outputPath);

            // run the analyzer
            using (var output = ProcessOutput.RunHiddenAndCapture("Microsoft.PythonTools.Analyzer.exe",
                                                                  "/lib", TestData.GetPath("TestData", "PathStdLib"),
                                                                  "/version", "2.7",
                                                                  "/outdir", outputPath,
                                                                  "/indir", CompletionDB,
                                                                  "/unittest",
                                                                  "/log", "AnalysisLog.txt")) {
                output.Wait();
                Console.WriteLine("* Stdout *");
                foreach (var line in output.StandardOutputLines)
                {
                    Console.WriteLine(line);
                }
                Console.WriteLine("* Stderr *");
                foreach (var line in output.StandardErrorLines)
                {
                    Console.WriteLine(line);
                }
                Assert.AreEqual(0, output.ExitCode);
            }

            File.Copy(Path.Combine(CompletionDB, "__builtin__.idb"), Path.Combine(outputPath, "__builtin__.idb"));

            var fact  = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7));
            var paths = new List <string> {
                outputPath
            };

            paths.AddRange(Directory.EnumerateDirectories(outputPath));
            var typeDb = new PythonTypeDatabase(fact, paths);
            var module = typeDb.GetModule("SomeLib");

            Assert.IsNotNull(module, "Could not import SomeLib");
            var fobMod = typeDb.GetModule("SomeLib.fob");

            Assert.IsNotNull(fobMod, "Could not import SomeLib.fob");

            var cClass = ((IPythonModule)fobMod).GetMember(null, "C");

            Assert.IsNotNull(cClass, "Could not get SomeLib.fob.C");

            Assert.AreEqual(PythonMemberType.Class, cClass.MemberType);
        }
示例#27
0
        internal async Task <IList <PipPackageView> > GetInstalledPackagesAsync()
        {
            string[] args;

            if (!CanExecute)
            {
                // Invalid configuration, so assume no packages
                return(null);
            }

            if (_factory.Configuration.Version < SupportsDashMPip)
            {
                args = new [] { "-c", "import pip; pip.main()", "list", "--no-index" };
            }
            else
            {
                args = new [] { "-m", "pip", "list", "--no-index" };
            }

            PipPackageView[] packages = null;

            try {
                using (var output = ProcessOutput.RunHiddenAndCapture(_factory.Configuration.InterpreterPath, args)) {
                    if ((await output) != 0)
                    {
                        throw new PipException(Resources.ListFailed);
                    }

                    packages = output.StandardOutputLines
                               .Select(s => new PipPackageView(_cache, s))
                               .ToArray();
                }
            } catch (IOException) {
            } finally {
                if (packages == null)
                {
                    // pip is obviously not installed
                    IsPipInstalled = false;
                }
                else
                {
                    // pip is obviously installed
                    IsPipInstalled = true;
                }
            }

            return(packages);
        }
示例#28
0
        private static async Task <ProcessOutputResult> RunPythonScript(string interpreterPath, string script, string parameters, bool showWindow = false)
        {
            ProcessOutput output    = null;
            var           arguments = string.Format("\"{0}\" {1}", script, parameters);

            if (showWindow)
            {
                output = ProcessOutput.RunVisible(interpreterPath, arguments);
            }
            else
            {
                output = ProcessOutput.RunHiddenAndCapture(interpreterPath, arguments);
            }

            return(await WaitForOutput(interpreterPath, output));
        }
示例#29
0
        private void StopPerfMon()
        {
            string perfToolsPath = GetPerfToolsPath();

            string perfMonPath = Path.Combine(perfToolsPath, "VSPerfCmd.exe");

            using (var p = ProcessOutput.RunHiddenAndCapture(perfMonPath, "/shutdown")) {
                p.Wait();
                if (p.ExitCode != 0)
                {
                    throw new InvalidOperationException(Strings.StopPerfMonError.FormatUI(
                                                            string.Join(Environment.NewLine, p.StandardOutputLines),
                                                            string.Join(Environment.NewLine, p.StandardErrorLines)
                                                            ));
                }
            }
        }
示例#30
0
        /// <summary>
        /// Activate the root conda environment, capture and return its environment variables
        /// </summary>
        /// <param name="condaPath">Path to the root conda environment's conda.exe</param>
        /// <returns>List of environment variables.</returns>
        internal async static Task <IEnumerable <KeyValuePair <string, string> > > CaptureActivationEnvironmentVariablesForRootAsync(string condaPath)
        {
            var activateBat = Path.Combine(Path.GetDirectoryName(condaPath), "activate.bat");

            if (File.Exists(activateBat))
            {
                using (var proc = ProcessOutput.RunHiddenAndCapture(activateBat, new[] { "&", "python.exe", "-c", PrintEnvironmentCode })) {
                    await proc;
                    if (proc.ExitCode == 0)
                    {
                        return(ParseEnvironmentVariables(proc));
                    }
                }
            }

            return(Enumerable.Empty <KeyValuePair <string, string> >());
        }