Try to restore a broken virtualenv by reinstalling the same python version on top of it
559978
def restore_cmd(argv):
    """"""

    if len(argv) < 1:
        sys.exit('You must provide a valid virtualenv to target')

    env = argv[0]
    path = workon_home / env
    py = path / env_bin_dir / ('python.exe' if windows else 'python')
    exact_py = py.resolve().name

    return check_call([sys.executable, "-m", "virtualenv", str(path.absolute()), "--python=%s" % exact_py])
22368
def restart_in_venv(venv, base, site_packages, args):
    
    if base and not os.path.isabs(venv) and not venv.startswith('~'):
        base = os.path.expanduser(base)
        # ensure we have an abs basepath at this point:
        #    a relative one makes no sense (or does it?)
        if os.path.isabs(base):
            venv = os.path.join(base, venv)

    if venv.startswith('~'):
        venv = os.path.expanduser(venv)

    if not os.path.exists(venv):
        try:
            import virtualenv
        except ImportError:
            print('The virtual environment does not exist: %s' % venv)
            print('and virtualenv is not installed, so a new environment cannot be created')
            sys.exit(3)
        print('Creating new virtualenv environment in %s' % venv)
        virtualenv.logger = logger
        logger.indent += 2
        virtualenv.create_environment(venv, site_packages=site_packages)
    if sys.platform == 'win32':
        python = os.path.join(venv, 'Scripts', 'python.exe')
        # check for bin directory which is used in buildouts
        if not os.path.exists(python):
            python = os.path.join(venv, 'bin', 'python.exe')
    else:
        python = os.path.join(venv, 'bin', 'python')
    if not os.path.exists(python):
        python = venv
    if not os.path.exists(python):
        raise BadCommand('Cannot find virtual environment interpreter at %s' % python)
    base = os.path.dirname(os.path.dirname(python))
    file = os.path.join(os.path.dirname(__file__), 'runner.py')
    if file.endswith('.pyc'):
        file = file[:-1]
    proc = subprocess.Popen(
        [python, file] + args + [base, '___VENV_RESTART___'])
    proc.wait()
    sys.exit(proc.returncode)
386089
def install(ctx, plugin):
    
    ensure_inside_venv(ctx)

    plugin_name = get_plugin_name(plugin)
    try:
        info = get_plugin_info(plugin_name)
    except NameError:
        echo_error("Plugin {} could not be found.".format(plugin))
        sys.exit(1)
    except ValueError as e:
        echo_error("Unable to retrieve plugin info. "
                   "Error was:\n\n {}".format(e))
        sys.exit(1)

    try:
        installed_version = pkg_resources.get_distribution(plugin_name).version
    except pkg_resources.DistributionNotFound:
        installed_version = None

    if installed_version is not None and info['version'] == installed_version:
        click.echo("You already have the latest version of {} ({}).".format(
            plugin, info['version']
        ))
        return

    pinned_plugin = '{0}=={1}'.format(plugin_name, info['version'])
    try:
        run_command([sys.executable, '-m', 'pip', 'install', pinned_plugin])
    except subprocess.CalledProcessError as e:
        echo_error("Error when trying to install plugin {}. "
                   "Error was:\n\n {}".format(plugin, e))
        sys.exit(1)

    echo_success("Plugin {} {} installed successfully.".format(
        plugin, info['version']
    ))
685317
def bootstrap_vi(version=None, venvargs=None):
    '''
    
    '''
    if not version:
        version = get_latest_virtualenv_version()
    tarball = download_virtualenv(version)
    p = subprocess.Popen('tar xzvf {0}'.format(tarball), shell=True)
    p.wait()
    p = 'virtualenv-{0}'.format(version)
    create_virtualenv(p, venvargs)
287181
def ensure_virtualenv(args, return_values):
    """"""
    def adjust_options(options, args):
        # TODO-TEST: proper error message with no arguments
        venv_path = return_values.venv_path = args[0]

        if venv_path == DEFAULT_VIRTUALENV_PATH or options.prompt == '<dirname>':
            from os.path import abspath, basename, dirname
            options.prompt = '(%s)' % basename(dirname(abspath(venv_path)))
        # end of option munging.

        # there are two python interpreters involved here:
        # 1) the interpreter we're instructing virtualenv to copy
        if options.python is None:
            source_python = None
        else:
            source_python = virtualenv.resolve_interpreter(options.python)
        # 2) the interpreter virtualenv will create
        destination_python = venv_python(venv_path)

        if exists(destination_python):
            reason = invalid_virtualenv_reason(venv_path, source_python, destination_python, options)
            if reason:
                info('Removing invalidated virtualenv. (%s)' % reason)
                run(('rm', '-rf', venv_path))
            else:
                info('Keeping valid virtualenv from previous run.')
                raise SystemExit(0)  # looks good! we're done here.

    # this is actually a documented extension point:
    #   http://virtualenv.readthedocs.org/en/latest/reference.html#adjust_options
    import virtualenv
    virtualenv.adjust_options = adjust_options

    from sys import argv
    argv[:] = ('virtualenv',) + args
    info(colorize(argv))
    raise_on_failure(virtualenv.main)
    # There might not be a venv_path if doing something like "venv= --version"
    # and not actually asking virtualenv to make a venv.
    if return_values.venv_path is not None:
        run(('rm', '-rf', join(return_values.venv_path, 'local')))
56129
def pip_create_virtualenv(path=None):
    """"""
    if six.PY2:
        apt_install('python-virtualenv')
    else:
        apt_install('python3-virtualenv')

    if path:
        venv_path = path
    else:
        venv_path = os.path.join(charm_dir(), 'venv')

    if not os.path.exists(venv_path):
        subprocess.check_call(['virtualenv', venv_path])
561658
def install(args):
    "  "

    # Deactivate virtualenv
    if 'VIRTUAL_ENV' in environ:
        LOGGER.warning('Virtualenv enabled: %s' % environ['VIRTUAL_ENV'])

    # Install from base modules
    if args.module:
        args.src = op.join(settings.MOD_DIR, args.module)
        assert op.exists(args.src), "Not found module: %s" % args.module

    # Fix project name
    args.PROJECT = args.PROJECT.replace('-', '_')

    args.home = op.abspath(args.path)

    # Create engine
    engine = Installer(args)
    args.deploy_dir = engine.target_dir

    # Check dir exists
    assert args.info or args.repeat or args.update or not op.exists(
        engine.target_dir), "Path %s exists. Stop deploy." % args.deploy_dir

    try:
        if args.repeat:
            site = Site(engine.target_dir)
            site.run_install()
            return site

        site = engine.clone_source()
        if not site:
            return True

        engine.build(args.update)
        site.run_install()
        return site

    except (CalledProcessError, AssertionError):
        LOGGER.error("Installation failed")
        LOGGER.error("Fix errors and repeat installation with (-r) or run 'makesite uninstall %s' for cancel." % args.deploy_dir)
        raise
870618
def main(argv, version=DEFAULT_VERSION):
    """"""
    try:
        import setuptools
    except ImportError:
        egg = None
        try:
            egg = download_setuptools(version, delay=0)
            sys.path.insert(0,egg)
            from setuptools.command.easy_install import main
            return main(list(argv)+[egg])   # we're done here
        finally:
            if egg and os.path.exists(egg):
                os.unlink(egg)
    else:
        if setuptools.__version__ == '0.0.1':
            print >>sys.stderr, (
            "You have an obsolete version of setuptools installed.  Please\n"
            "remove it from your system entirely before rerunning this script."
            )
            sys.exit(2)

    req = "setuptools>="+version
    import pkg_resources
    try:
        pkg_resources.require(req)
    except pkg_resources.VersionConflict:
        try:
            from setuptools.command.easy_install import main
        except ImportError:
            from easy_install import main
        main(list(argv)+[download_setuptools(delay=0)])
        sys.exit(0) # try to force an exit
    else:
        if argv:
            from setuptools.command.easy_install import main
            main(argv)
        else:
            print "Setuptools version",version,"or greater has been installed."
            print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
1346386
def install_package_to_venv(self):
        '''
        
        '''
        try:
            self.env.install(self.name, force=True, options=["--no-deps"])
        except (ve.PackageInstallationException,
                ve.VirtualenvReadonlyException):
            raise VirtualenvFailException(
                'Failed to install package to virtualenv')
        self.dirs_after_install.fill(self.temp_dir + '/venv/')
996237
def create_venv(requested_deps, interpreter, is_current, options, pip_options):
    """"""
    # create virtualenv
    env = _FadesEnvBuilder()
    env_path, env_bin_path, pip_installed = env.create_env(interpreter, is_current, options)
    venv_data = {}
    venv_data['env_path'] = env_path
    venv_data['env_bin_path'] = env_bin_path
    venv_data['pip_installed'] = pip_installed

    # install deps
    installed = {}
    for repo in requested_deps.keys():
        if repo in (REPO_PYPI, REPO_VCS):
            mgr = PipManager(env_bin_path, pip_installed=pip_installed, options=pip_options)
        else:
            logger.warning("Install from %r not implemented", repo)
            continue
        installed[repo] = {}

        repo_requested = requested_deps[repo]
        logger.debug("Installing dependencies for repo %r: requested=%s", repo, repo_requested)
        for dependency in repo_requested:
            try:
                mgr.install(dependency)
            except Exception:
                logger.debug("Installation Step failed, removing virtualenv")
                destroy_venv(env_path)
                raise FadesError('Dependency installation failed')

            if repo == REPO_VCS:
                # no need to request the installed version, as we'll always compare
                # to the url itself
                project = dependency.url
                version = None
            else:
                # always store the installed dependency, as in the future we'll select the venv
                # based on what is installed, not what used requested (remember that user may
                # request >, >=, etc!)
                project = dependency.project_name
                version = mgr.get_version(project)
            installed[repo][project] = version

        logger.debug("Installed dependencies: %s", installed)
    return venv_data, installed
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')
651916
def reset(name):
    '''
    
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        __jid_event__.fire_event({'message': 'Failed to find VM {0} to reset'.format(name)}, 'progress')
        return 'fail'
    host = next(six.iterkeys(data))
    try:
        cmd_ret = client.cmd_iter(
                host,
                'virt.reset',
                [name],
                timeout=600)
        for comp in cmd_ret:
            ret.update(comp)
        __jid_event__.fire_event({'message': 'Reset VM {0}'.format(name)}, 'progress')
    except SaltClientError as client_error:
        print(client_error)
    return ret
29460
def reinstall(self):
        
        with _LOCK:
            if not (self.thread.is_alive() and self.thread in _ORIGINAL__ACTIVE):
                self.thread = self.thread.clone(bind_delay=self.reinstall_delay)
                if self.should_restart:
                    self.thread.start()
734448
def create_virtualenv(venv=VENV):
    
    print 'Creating venv...',
    run_command(['virtualenv', '-q', '--no-site-packages', VENV])
    print 'done.'
    print 'Installing pip in virtualenv...',
    if not run_command([WITH_VENV, 'easy_install', 'pip']).strip():
        die("Failed to install pip.")
    print 'done.'
    print 'Installing distribute in virtualenv...'
    pip_install('distribute>=0.6.24')
    print 'done.'
189466
def restart_program():
    
    logging.debug("Restarting program...")
    python = sys.executable
    os.execl(python, python, * sys.argv)
1262552
def reboot(*args):
    
    args = list(sys.argv) + list(args)
    if args[0] == 'python' or not args[0]:
        args[0] = BIN_PYTHON
    elif os.path.basename(sys.argv[0]) in ['lore', 'lore.exe']:
        args[0] = BIN_LORE
    try:
        os.execv(args[0], args)
    except Exception as e:
        if args[0] == BIN_LORE and args[1] == 'console' and JUPYTER_KERNEL_PATH:
            print(ansi.error() + ' Your jupyter kernel may be corrupt. Please remove it so lore can reinstall:\n $ rm ' + JUPYTER_KERNEL_PATH)
        raise e
820326
def restore(self):
        """"""
        signal.signal(signal.SIGINT, self.original_sigint)
        signal.signal(signal.SIGTERM, self.original_sigterm)
        if os.name == 'nt':
            signal.signal(signal.SIGBREAK, self.original_sigbreak)