Create the virtualenv and return its info.
175386
def create_env(self, interpreter, is_current, options):
        """"""
        if is_current:
            # apply pyvenv options
            pyvenv_options = options['pyvenv_options']
            if "--system-site-packages" in pyvenv_options:
                self.system_site_packages = True
            logger.debug("Creating virtualenv with pyvenv. options=%s", pyvenv_options)
            self.create(self.env_path)
        else:
            virtualenv_options = options['virtualenv_options']
            logger.debug("Creating virtualenv with virtualenv")
            self.create_with_virtualenv(interpreter, virtualenv_options)
        logger.debug("env_bin_path: %s", self.env_bin_path)

        # Re check if pip was installed (supporting both binary and .exe for Windows)
        pip_bin = os.path.join(self.env_bin_path, "pip")
        pip_exe = os.path.join(self.env_bin_path, "pip.exe")
        if not (os.path.exists(pip_bin) or os.path.exists(pip_exe)):
            logger.debug("pip isn't installed in the venv, setting pip_installed=False")
            self.pip_installed = False

        return self.env_path, self.env_bin_path, self.pip_installed
850739
def install_virtualenv_p3(root, python_version):
    
    import venv
    builder = venv.EnvBuilder(system_site_packages=False, clear=True, symlinks=False, upgrade=False)
    builder.create(root)
    ret_code = subprocess.call([VE_SCRIPT, PROJECT_ROOT, root, python_version])
    sys.exit(ret_code)
626630
def install_virtualenv_p2(root, python_version):
    
    try:
        import virtualenv
    except ImportError:
        sys.stdout.write('Installing virtualenv into global interpreter \n')
        ret_code = subprocess.call([VE_GLOBAL_SCRIPT, PROJECT_ROOT])
        sys.stdout.write('Installation finished with code {0}. Re-run ./launch.py install \n'.format(ret_code))
        sys.exit(ret_code)

    if path.exists(root):
        shutil.rmtree(root)
    virtualenv.logger = virtualenv.Logger(consumers=[])
    virtualenv.create_environment(root, site_packages=False)
    ret_code = subprocess.call([VE_SCRIPT, PROJECT_ROOT, root, python_version])
    sys.exit(ret_code)
9703
def get_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str:
        
        return str(self.get_or_create_venv(repo_path).resolve() / "bin" / "python")
915055
def create(vm_):
    '''
    

    '''
    name = vm_['name']
    machine = config.get_cloud_config_value(
        'machine', vm_, __opts__, default='')
    vm_['machine'] = machine
    host = config.get_cloud_config_value(
        'host', vm_, __opts__, default=NotImplemented)
    vm_['cwd'] = config.get_cloud_config_value(
        'cwd', vm_, __opts__, default='/')
    vm_['runas'] = config.get_cloud_config_value(
        'vagrant_runas', vm_, __opts__, default=os.getenv('SUDO_USER'))
    vm_['timeout'] = config.get_cloud_config_value(
        'vagrant_up_timeout', vm_, __opts__, default=300)
    vm_['vagrant_provider'] = config.get_cloud_config_value(
        'vagrant_provider', vm_, __opts__, default='')
    vm_['grains'] = {'salt-cloud:vagrant': {'host': host, 'machine': machine}}

    log.info('sending \'vagrant.init %s machine=%s\' command to %s', name, machine, host)

    local = salt.client.LocalClient()
    ret = local.cmd(host, 'vagrant.init', [name], kwarg={'vm': vm_, 'start': True})
    log.info('response ==> %s', ret[host])

    network_mask = config.get_cloud_config_value(
        'network_mask', vm_, __opts__, default='')
    if 'ssh_host' not in vm_:
        ret = local.cmd(host,
                        'vagrant.get_ssh_config',
                        [name],
                        kwarg={'network_mask': network_mask,
                                'get_private_key': True})[host]
    with tempfile.NamedTemporaryFile() as pks:
        if 'private_key' not in vm_ and ret and ret.get('private_key', False):
            pks.write(ret['private_key'])
            pks.flush()
            log.debug('wrote private key to %s', pks.name)
            vm_['key_filename'] = pks.name
        if 'ssh_host' not in vm_:
            try:
                vm_.setdefault('ssh_username', ret['ssh_username'])
                if ret.get('ip_address'):
                    vm_['ssh_host'] = ret['ip_address']
                else:  # if probe failed or not used, use Vagrant's reported ssh info
                    vm_['ssh_host'] = ret['ssh_host']
                    vm_.setdefault('ssh_port', ret['ssh_port'])
            except (KeyError, TypeError):
                raise SaltInvocationError(
                    'Insufficient SSH addressing information for {}'.format(name))

        log.info('Provisioning machine %s as node %s using ssh %s',
                 machine, name, vm_['ssh_host'])
        ret = __utils__['cloud.bootstrap'](vm_, __opts__)
        return ret
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')))
370802
def create_vm(self, userid, cpu, memory, disk_list,
                  user_profile, max_cpu, max_mem, ipl_from,
                  ipl_param, ipl_loadparam):
        """"""
        LOG.info("Creating the user directory for vm %s", userid)

        info = self._smtclient.create_vm(userid, cpu, memory,
                                   disk_list, user_profile,
                                   max_cpu, max_mem, ipl_from,
                                   ipl_param, ipl_loadparam)

        # add userid into smapi namelist
        self._smtclient.namelist_add(self._namelist, userid)
        return info
317953
def create_result(self, env_name, other_val, meta, val, dividers):
        """"""
        args = [env_name]
        if other_val is NotSpecified:
            other_val = None
        if not dividers:
            args.extend([None, None])
        elif dividers[0] == ':':
            args.extend([other_val, None])
        elif dividers[0] == '=':
            args.extend([None, other_val])
        return Environment(*args)
1146204
def mkvirtualenv():
    
    root = '/'.join([deployment_root(),'env'])
    path = '/'.join([root,env.project_fullname])
    dirs_created = []
    if env.verbosity:
        print env.host,'CREATING VIRTUALENV', path
    if not exists(root): dirs_created += mkdirs(root)
    with cd(root):
        run(' '.join(["virtualenv",env.project_fullname]))
    with cd(path):
        dirs_created += mkdirs('egg_cache')
        sudo('chown -R %s:www-data egg_cache'% env.user)
        sudo('chmod -R g+w egg_cache')
        run(''.join(["echo 'cd ",path,'/','project','/',env.project_package_name,'/sitesettings',"' > bin/postactivate"]))
        sudo('chmod ugo+rwx bin/postactivate')

    #Create a state
    out = State(' '.join([env.host,'virtualenv',path,'created']))
    out.object = dirs_created + ['bin','lib','include']
    out.failed = False
    return out
455738
def create_venv(local='y', test='y', general='y'):
    """"""
    if not path.isdir(project_paths.venv):
        execute('virtualenv', '--distribute', '--no-site-packages', project_paths.venv)
        project.execute_python('-m', 'easy_install', 'pip')
    if local.lower() == 'y' and project_paths.local_requirements:
        project.execute_pip('install', '--upgrade', '-r', project_paths.local_requirements)
    if test.lower() == 'y' and project_paths.test_requirements:
        project.execute_pip('install', '--upgrade', '-r', project_paths.test_requirements)
    if general.lower() == 'y' and project_paths.requirements_txt:
        project.execute_pip('install', '--upgrade', '-r', project_paths.requirements_txt)
991788
def dir_cmd(argv):
    """"""
    env = parse_envname(argv, lambda : sys.exit('You must provide a valid virtualenv to target'))
    print(workon_home / env)
831811
def create_api_v4_virtual_interface(self):
        """"""
        return ApiV4VirtualInterface(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
288076
def prep_shell_environment(nova_env, nova_creds):
    
    new_env = {}

    for key, value in prep_nova_creds(nova_env, nova_creds):
        if type(value) == six.binary_type:
            value = value.decode()
        new_env[key] = value

    return new_env
8171
def create_vm(self, userid, cpu, memory, disk_list, profile,
                  max_cpu, max_mem, ipl_from, ipl_param, ipl_loadparam):
        
        rd = ('makevm %(uid)s directory LBYONLY %(mem)im %(pri)s '
              '--cpus %(cpu)i --profile %(prof)s --maxCPU %(max_cpu)i '
              '--maxMemSize %(max_mem)s --setReservedMem' %
              {'uid': userid, 'mem': memory,
               'pri': const.ZVM_USER_DEFAULT_PRIVILEGE,
               'cpu': cpu, 'prof': profile,
               'max_cpu': max_cpu, 'max_mem': max_mem})

        if CONF.zvm.default_admin_userid:
            rd += (' --logonby "%s"' % CONF.zvm.default_admin_userid)

        if (disk_list and 'is_boot_disk' in disk_list[0] and
            disk_list[0]['is_boot_disk']):
            # we assume at least one disk exist, which means, is_boot_disk
            # is true for exactly one disk.
            rd += (' --ipl %s' % self._get_ipl_param(ipl_from))

            # load param for ipl
            if ipl_param:
                rd += ' --iplParam %s' % ipl_param

            if ipl_loadparam:
                rd += ' --iplLoadparam %s' % ipl_loadparam

        action = "create userid '%s'" % userid

        try:
            self._request(rd)
        except exception.SDKSMTRequestFailed as err:
            if ((err.results['rc'] == 436) and (err.results['rs'] == 4)):
                result = "Profile '%s'" % profile
                raise exception.SDKObjectNotExistError(obj_desc=result,
                                                       modID='guest')
            else:
                msg = ''
                if action is not None:
                    msg = "Failed to %s. " % action
                msg += "SMT error: %s" % err.format_message()
                LOG.error(msg)
                raise exception.SDKSMTRequestFailed(err.results, msg)

        # Add the guest to db immediately after user created
        action = "add guest '%s' to database" % userid
        with zvmutils.log_and_reraise_sdkbase_error(action):
            self._GuestDbOperator.add_guest(userid)

        # Continue to add disk
        if disk_list:
            # Add disks for vm
            return self.add_mdisks(userid, disk_list)
428086
def _get_system_python_executable():
    
    # This function is required by get_package_as_folder() to work
    # inside a virtualenv, since venv creation will fail with
    # the virtualenv's local python binary.
    # (venv/virtualenv incompatibility)

    # Abort if not in virtualenv or venv:
    if not hasattr(sys, "real_prefix") and (
            not hasattr(sys, "base_prefix") or
            os.path.normpath(sys.base_prefix) ==
            os.path.normpath(sys.prefix)):
        return sys.executable

    # Extract prefix we need to look in:
    if hasattr(sys, "real_prefix"):
        search_prefix = sys.real_prefix  # virtualenv
    else:
        search_prefix = sys.base_prefix  # venv

    def python_binary_from_folder(path):
        def binary_is_usable(python_bin):
            try:
                filenotfounderror = FileNotFoundError
            except NameError:  # Python 2
                filenotfounderror = OSError
            try:
                subprocess.check_output([
                    os.path.join(path, python_bin), "--version"
                ], stderr=subprocess.STDOUT)
                return True
            except (subprocess.CalledProcessError, filenotfounderror):
                return False

        python_name = "python" + sys.version
        while (not binary_is_usable(python_name) and
               python_name.find(".") > 0):
            # Try less specific binary name:
            python_name = python_name.rpartition(".")[0]
        if binary_is_usable(python_name):
            return os.path.join(path, python_name)
        return None

    # Return from sys.real_prefix if present:
    result = python_binary_from_folder(search_prefix)
    if result is not None:
        return result

    # Check out all paths in $PATH:
    bad_candidates = []
    good_candidates = []
    ever_had_nonvenv_path = False
    for p in os.environ.get("PATH", "").split(":"):
        # Skip if not possibly the real system python:
        if not os.path.normpath(p).startswith(
                os.path.normpath(search_prefix)
                ):
            continue

        # First folders might be virtualenv/venv we want to avoid:
        if not ever_had_nonvenv_path:
            sep = os.path.sep
            if ("system32" not in p.lower() and "usr" not in p) or \
                    {"home", ".tox"}.intersection(set(p.split(sep))) or \
                    "users" in p.lower():
                # Doesn't look like bog-standard system path.
                if (p.endswith(os.path.sep + "bin") or
                        p.endswith(os.path.sep + "bin" + os.path.sep)):
                    # Also ends in "bin" -> likely virtualenv/venv.
                    # Add as unfavorable / end of candidates:
                    bad_candidates.append(p)
                    continue
            ever_had_nonvenv_path = True

        good_candidates.append(p)

    # See if we can now actually find the system python:
    for p in good_candidates + bad_candidates:
        result = python_binary_from_folder(p)
        if result is not None:
            return result

    raise RuntimeError("failed to locate system python in: " +
                       sys.real_prefix)
282985
def make_env(env_type, real_env, sim_env_kwargs):
  """"""
  return {
      "real": lambda: real_env.new_like(  # pylint: disable=g-long-lambda
          batch_size=sim_env_kwargs["batch_size"],
          store_rollouts=False,
      ),
      "simulated": lambda: rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames(  # pylint: disable=g-long-lambda
          **sim_env_kwargs
      ),
  }[env_type]()
984607
def SetupVars(self):
    """"""
    # Python paths chosen to match appveyor:
    # http://www.appveyor.com/docs/installed-software#python

    self.python_dir_64 = args.python64_dir
    self.python_dir_32 = args.python32_dir

    self.virtualenv_bin64 = os.path.join(self.python_dir_64,
                                         r"Scripts\virtualenv.exe")
    self.virtualenv_bin32 = os.path.join(self.python_dir_32,
                                         r"Scripts\virtualenv.exe")

    if args.virtualenv_64bit:
      self.virtualenv64 = args.virtualenv_64bit
    else:
      self.virtualenv64 = os.path.join(args.build_dir, "python_64")
    if args.virtualenv_32bit:
      self.virtualenv32 = args.virtualenv_32bit
    else:
      self.virtualenv32 = os.path.join(args.build_dir, "python_32")

    self.grr_client_build64 = os.path.join(self.virtualenv64,
                                           r"Scripts\grr_client_build.exe")
    self.grr_client_build32 = os.path.join(self.virtualenv32,
                                           r"Scripts\grr_client_build.exe")
    self.pip64 = os.path.join(self.virtualenv64, r"Scripts\pip.exe")
    self.pip32 = os.path.join(self.virtualenv32, r"Scripts\pip.exe")

    self.virtualenv_python64 = os.path.join(self.virtualenv64,
                                            r"Scripts\python.exe")
    self.virtualenv_python32 = os.path.join(self.virtualenv32,
                                            r"Scripts\python.exe")

    self.git = r"C:\Program Files\Git\bin\git.exe"

    self.install_path = r"C:\Windows\System32\GRR"
    self.service_name = "GRR Monitor"

    self.expect_service_running = args.expect_service_running