Install Required Libraries using pip.
171347
def install_libs(self):
        """"""
        # default or current python version
        lib_data = [{'python_executable': sys.executable, 'lib_dir': self.lib_directory}]

        # check for requirements.txt
        if not os.path.isfile(self.requirements_file):
            self.handle_error('A requirements.txt file is required to install modules.')

        # if branch arg is provide use git branch instead of pypi
        if self.args.branch is not None:
            self._create_temp_requirements()

        # overwrite default with config data
        if self.tcex_json.get('lib_versions'):
            lib_data = self.tcex_json.get('lib_versions')
            print('{}Using "lib" directories defined in tcex.json file.'.format(c.Style.BRIGHT))

        # configure proxy settings
        proxy_enabled = self._configure_proxy()

        # install all requested lib directories
        for data in lib_data:
            # pattern to match env vars in data
            env_var = re.compile(r'\$env\.([a-zA-Z0-9]+)')

            lib_dir = data.get('lib_dir')
            # replace env vars with env val in the lib dir
            matches = re.findall(env_var, lib_dir)
            if matches:
                env_val = os.environ.get(matches[0])
                if env_val is None:
                    self.handle_error(
                        '"{}" env variable set in tcex.json, but could not be resolved.'.format(
                            matches[0]
                        )
                    )
                lib_dir = re.sub(env_var, env_val, lib_dir)
            lib_dir_fq = os.path.join(self.app_path, lib_dir)

            if os.access(lib_dir_fq, os.W_OK):
                # remove lib directory from previous runs
                shutil.rmtree(lib_dir_fq)

            # replace env vars with env val in the python executable
            python_executable = data.get('python_executable')
            matches = re.findall(env_var, python_executable)
            if matches:
                env_val = os.environ.get(matches[0])
                python_executable = re.sub(env_var, env_val, python_executable)

            print('Building Lib Dir: {}{}{}'.format(c.Style.BRIGHT, c.Fore.CYAN, lib_dir_fq))
            exe_command = self._build_command(python_executable, lib_dir_fq, proxy_enabled)

            print('Running: {}{}{}'.format(c.Style.BRIGHT, c.Fore.GREEN, ' '.join(exe_command)))
            p = subprocess.Popen(
                exe_command,
                shell=False,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            out, err = p.communicate()  # pylint: disable=W0612

            if p.returncode != 0:
                print('{}{}FAIL'.format(c.Style.BRIGHT, c.Fore.RED))
                print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, err.decode('utf-8')))
                sys.exit('ERROR: {}'.format(err.decode('utf-8')))

            # version comparison
            try:
                python_version = lib_dir.split('_', 1)[1]
            except IndexError:
                self.handle_error('Could not determine version from lib string.')

            # track the latest Python version
            if self.latest_version is None:
                self.latest_version = python_version
            elif StrictVersion(python_version) > StrictVersion(self.latest_version):
                self.latest_version = python_version

        # cleanup temp file if required
        if self.use_temp_requirements_file:
            os.remove(self.requirements_file)

        # create lib_latest
        self._create_lib_latest()
775112
def pipinstall(packages):
    

    if isinstance(packages, str):
        if hasattr(pip, 'main'):
            pip.main(['install', packages])
        else:
            pip._internal.main(['install', packages])
    elif isinstance(packages, list):
        for i in enumerate(packages):
            if hasattr(pip, 'main'):
                pip.main(['install', i[1]])
            else:
                pip._internal.main(['install', i[1]])
    else:
        raise TypeError("Nor a string or a list was provided.")
534698
def _brute_force_install_pip(self):
        """"""
        if os.path.exists(self.pip_installer_fname):
            logger.debug("Using pip installer from %r", self.pip_installer_fname)
        else:
            logger.debug(
                "Installer for pip not found in %r, downloading it", self.pip_installer_fname)
            self._download_pip_installer()

        logger.debug("Installing PIP manually in the virtualenv")
        python_exe = os.path.join(self.env_bin_path, "python")
        helpers.logged_exec([python_exe, self.pip_installer_fname, '-I'])
        self.pip_installed = True
137850
def install(name, link, path, priority):
    '''
    
    '''
    cmd = [_get_cmd(), '--install', link, name, path, six.text_type(priority)]
    out = __salt__['cmd.run_all'](cmd, python_shell=False)
    if out['retcode'] > 0 and out['stderr'] != '':
        return out['stderr']
    return out['stdout']
932856
def create_pipfile(self, python=None):
        """"""
        from .vendor.pip_shims.shims import (
            ConfigOptionParser, make_option_group, index_group
        )

        config_parser = ConfigOptionParser(name=self.name)
        config_parser.add_option_group(make_option_group(index_group, config_parser))
        install = config_parser.option_groups[0]
        indexes = (
            " ".join(install.get_option("--extra-index-url").default)
            .lstrip("\n")
            .split("\n")
        )
        sources = [DEFAULT_SOURCE,]
        for i, index in enumerate(indexes):
            if not index:
                continue

            source_name = "pip_index_{}".format(i)
            verify_ssl = index.startswith("https")
            sources.append(
                {u"url": index, u"verify_ssl": verify_ssl, u"name": source_name}
            )

        data = {
            u"source": sources,
            # Default packages.
            u"packages": {},
            u"dev-packages": {},
        }
        # Default requires.
        required_python = python
        if not python:
            if self.virtualenv_location:
                required_python = self.which("python", self.virtualenv_location)
            else:
                required_python = self.which("python")
        version = python_version(required_python) or PIPENV_DEFAULT_PYTHON_VERSION
        if version and len(version) >= 3:
            data[u"requires"] = {"python_version": version[: len("2.7")]}
        self.write_toml(data)
1034294
def install(packagename, save, save_dev, save_test, filename):
    
    print('Installing ', packagename)
    print(sh_pip.install(packagename))
    if not filename:
        filename = get_filename(save, save_dev, save_test)
    try:
        add_requirements(packagename, filename)
    except AssertionError:
        print('Package already pinned in ', filename)
667168
def install_dependencies(self):
        '''  '''
        # If virtualenv is set to skip then do nothing
        if self._skip_virtualenv:
            LOG.info('Skip Virtualenv set ... nothing to do')
            return

        has_reqs = _isfile(self._requirements_file) or self._requirements
        if self._virtualenv is None and has_reqs:
            LOG.info('Building new virtualenv and installing requirements')
            self._build_new_virtualenv()
            self._install_requirements()
        elif self._virtualenv is None and not has_reqs:
            LOG.info('No requirements found, so no virtualenv will be made')
            self._pkg_venv = False
        else:
            raise Exception('Cannot determine what to do about virtualenv')
68392
def main(argv=sys.argv):
    """"""
    parser = setup_parser()

    (opts, args) = parser.parse_args(argv[1:])

    if not args:
        parser.error('A package path is required.')

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error('An output directory is required.')
    if opts.header is None:
        opts.header = path.normpath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith('.'):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print >>sys.stderr, '%s is not a directory.' % rootpath
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    rootpath = path.normpath(path.abspath(rootpath))
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx import quickstart as qs
        modules.sort()
        prev_module = ''
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path = opts.destdir,
            sep  = False,
            dot  = '_',
            project = opts.header,
            author = opts.author or 'Author',
            version = opts.version or '',
            release = opts.release or opts.version or '',
            suffix = '.' + opts.suffix,
            master = 'index',
            epub = True,
            ext_autodoc = True,
            ext_viewcode = True,
            makefile = True,
            batchfile = True,
            mastertocmaxdepth = opts.maxdepth,
            mastertoctree = text,
        )
        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
773596
def main(requirements_file, skip_requirements_file, pipfile, skip_pipfile):
    # type: (str, bool, str, bool) -> None
    """"""
    pipfile_path = path.Path(pipfile)
    pf = load_pipfile(pipfile_path)

    if not skip_requirements_file:
        requirements_file_path = path.Path(requirements_file)
        update_requirements(requirements_file_path, pf)

    if not skip_pipfile:
        dump_pipfile(pipfile_path, pf)
553107
def pip(name):
    ''''''
    with io.open(os.path.join('requirements', '{0}.pip'.format(name))) as f:
        return f.readlines()
865907
def pip_install(package, fatal=False, upgrade=False, venv=None,
                constraints=None, **options):
    """"""
    if venv:
        venv_python = os.path.join(venv, 'bin/pip')
        command = [venv_python, "install"]
    else:
        command = ["install"]

    available_options = ('proxy', 'src', 'log', 'index-url', )
    for option in parse_options(options, available_options):
        command.append(option)

    if upgrade:
        command.append('--upgrade')

    if constraints:
        command.extend(['-c', constraints])

    if isinstance(package, list):
        command.extend(package)
    else:
        command.append(package)

    log("Installing {} package with options: {}".format(package,
                                                        command))
    if venv:
        subprocess.check_call(command)
    else:
        pip_execute(command)
765373
def _ensure_dependency_available_at_version(package_name, min_version):
  """"""

  try:
    pkg = importlib.import_module(package_name)
  except ImportError:
    pip_name = package_name.replace('_', '-')
    raise SystemError(
        'Sonnet requires %s (minimum version %s) to be installed. '
        'If using pip, run `pip install %s` or '
        '`pip install %s-gpu`' % (
            package_name, min_version, pip_name, pip_name))

  installed_version = semantic_version.Version(pkg.__version__)
  version_spec = semantic_version.Spec('>=' + min_version)
  if not version_spec.match(installed_version):
    raise SystemError(
        '%s version %s is installed, but Sonnet requires at least version %s.' %
        (package_name, pkg.__version__, min_version))
1167235
def python_dependencies(context: Context, extras=None):
    
    with mock.patch('setuptools.setup'):
        from setup import install_requires, extras_require

        requirements = install_requires.copy()
        if extras:
            requirements.extend(extras_require[extras])
    return context.pip_command('install', *requirements)
494415
def ensure_packages(packages):
    """"""
    required = filter_installed_packages(packages)
    if required:
        apt_install(required, fatal=True)
765807
def install(self):
        """"""
        project_dir = os.path.dirname(self.classpath_file)
        sbt_plugin = """addSbtPlugin("{0}" % "{1}" % "{2}")"""

        Util.mkdir_p(project_dir)
        Util.mkdir_p(os.path.join(project_dir, "project"))
        Util.write_file(
            os.path.join(project_dir, "build.sbt"),
            self.build_sbt())
        Util.write_file(
            os.path.join(project_dir, "project", "build.properties"),
            "sbt.version={}".format(self.SBT_VERSION))
        Util.write_file(
            os.path.join(project_dir, "project", "plugins.sbt"),
            sbt_plugin.format(*self.SBT_COURSIER_COORDS))

        # Synchronous update of the classpath via sbt
        # see https://github.com/ensime/ensime-vim/issues/29
        cd_cmd = "cd {}".format(project_dir)
        sbt_cmd = "sbt -Dsbt.log.noformat=true -batch saveClasspath"

        if int(self.vim.eval("has('nvim')")):
            import tempfile
            import re
            tmp_dir = tempfile.gettempdir()
            flag_file = "{}/ensime-vim-classpath.flag".format(tmp_dir)
            self.vim.command("echo 'Waiting for generation of classpath...'")
            if re.match(".+fish$", self.vim.eval("&shell")):
                sbt_cmd += "; echo $status > {}".format(flag_file)
                self.vim.command("terminal {}; and {}".format(cd_cmd, sbt_cmd))
            else:
                sbt_cmd += "; echo $? > {}".format(flag_file)
                self.vim.command("terminal ({} && {})".format(cd_cmd, sbt_cmd))

            # Block execution when sbt is run
            waiting_for_flag = True
            while waiting_for_flag:
                waiting_for_flag = not os.path.isfile(flag_file)
                if not waiting_for_flag:
                    with open(flag_file, "r") as f:
                        rtcode = f.readline()
                    os.remove(flag_file)
                    if rtcode and int(rtcode) != 0:  # error
                        self.vim.command(
                            "echo 'Something wrong happened, check the "
                            "execution log...'")
                        return None
                else:
                    time.sleep(0.2)
        else:
            self.vim.command("!({} && {})".format(cd_cmd, sbt_cmd))

        success = self.reorder_classpath(self.classpath_file)
        if not success:
            self.vim.command("echo 'Classpath ordering failed.'")

        return True
303252
def pip_compile(*packages: str):
    """"""
    result = None
    packages = "\n".join(packages)

    with tempfile.TemporaryDirectory() as tmp_dirname, cwd(tmp_dirname):
        with open("requirements.in", "w") as requirements_file:
            requirements_file.write(packages)

        runner = CliRunner()

        try:
            result = runner.invoke(cli, ["requirements.in"], catch_exceptions=False)
        except Exception as exc:
            raise ThothPipCompileError(str(exc)) from exc

        if result.exit_code != 0:
            error_msg = (
                f"pip-compile returned non-zero ({result.exit_code:d}) " f"output: {result.output_bytes.decode():s}"
            )
            raise ThothPipCompileError(error_msg)

    return result.output_bytes.decode()
682778
def install_from_pypi(context):
    """"""

    tmp_dir = venv.create_venv()
    install_cmd = '%s/bin/pip install %s' % (tmp_dir, context.module_name)

    package_index = 'pypi'
    if context.pypi:
        install_cmd += '-i %s' % context.pypi
        package_index = context.pypi

    try:
        result = shell.dry_run(install_cmd, context.dry_run)
        if not context.dry_run and not result:
            log.error(
                'Failed to install %s from %s', context.module_name, package_index
            )
        else:
            log.info(
                'Successfully installed %s from %s', context.module_name, package_index
            )

    except Exception as e:
        error_msg = 'Error installing %s from %s' % (context.module_name, package_index)
        log.exception(error_msg)
        raise Exception(error_msg, e)