Create a project-level virtualenv (if it does not already exist).

    :return: ``VirtualEnv`` object
427373
def get_or_create_project_venv():
    
    venv_dir = get_project_venv_dir()

    if os.path.exists(venv_dir):
        return VirtualEnv(venv_dir)
    else:
        return create_project_venv()
1361794
def do_init(
    dev=False,
    requirements=False,
    allow_global=False,
    ignore_pipfile=False,
    skip_lock=False,
    system=False,
    concurrent=True,
    deploy=False,
    pre=False,
    keep_outdated=False,
    requirements_dir=None,
    pypi_mirror=None,
):
    """"""
    from .environments import (
        PIPENV_VIRTUALENV, PIPENV_DEFAULT_PYTHON_VERSION, PIPENV_PYTHON, PIPENV_USE_SYSTEM
    )
    python = None
    if PIPENV_PYTHON is not None:
        python = PIPENV_PYTHON
    elif PIPENV_DEFAULT_PYTHON_VERSION is not None:
        python = PIPENV_DEFAULT_PYTHON_VERSION

    if not system and not PIPENV_USE_SYSTEM:
        if not project.virtualenv_exists:
            try:
                do_create_virtualenv(python=python, three=None, pypi_mirror=pypi_mirror)
            except KeyboardInterrupt:
                cleanup_virtualenv(bare=False)
                sys.exit(1)
    # Ensure the Pipfile exists.
    if not deploy:
        ensure_pipfile(system=system)
    if not requirements_dir:
        requirements_dir = vistir.path.create_tracked_tempdir(
            suffix="-requirements", prefix="pipenv-"
        )
    # Write out the lockfile if it doesn't exist, but not if the Pipfile is being ignored
    if (project.lockfile_exists and not ignore_pipfile) and not skip_lock:
        old_hash = project.get_lockfile_hash()
        new_hash = project.calculate_pipfile_hash()
        if new_hash != old_hash:
            if deploy:
                click.echo(
                    crayons.red(
                        "Your Pipfile.lock ({0}) is out of date. Expected: ({1}).".format(
                            old_hash[-6:], new_hash[-6:]
                        )
                    )
                )
                raise exceptions.DeployException
                sys.exit(1)
            elif (system or allow_global) and not (PIPENV_VIRTUALENV):
                click.echo(
                    crayons.red(fix_utf8(
                        "Pipfile.lock ({0}) out of date, but installation "
                        "uses {1}… re-building lockfile must happen in "
                        "isolation. Please rebuild lockfile in a virtualenv. "
                        "Continuing anyway…".format(
                            crayons.white(old_hash[-6:]), crayons.white("--system")
                        )),
                        bold=True,
                    ),
                    err=True,
                )
            else:
                if old_hash:
                    msg = fix_utf8("Pipfile.lock ({0}) out of date, updating to ({1})…")
                else:
                    msg = fix_utf8("Pipfile.lock is corrupted, replaced with ({1})…")
                click.echo(
                    crayons.red(msg.format(old_hash[-6:], new_hash[-6:]), bold=True),
                    err=True,
                )
                do_lock(
                    system=system,
                    pre=pre,
                    keep_outdated=keep_outdated,
                    write=True,
                    pypi_mirror=pypi_mirror,
                )
    # Write out the lockfile if it doesn't exist.
    if not project.lockfile_exists and not skip_lock:
        # Unless we're in a virtualenv not managed by pipenv, abort if we're
        # using the system's python.
        if (system or allow_global) and not (PIPENV_VIRTUALENV):
            raise exceptions.PipenvOptionsError(
                "--system",
                "--system is intended to be used for Pipfile installation, "
                "not installation of specific packages. Aborting.\n"
                "See also: --deploy flag."
            )
        else:
            click.echo(
                crayons.normal(fix_utf8("Pipfile.lock not found, creating…"), bold=True),
                err=True,
            )
            do_lock(
                system=system,
                pre=pre,
                keep_outdated=keep_outdated,
                write=True,
                pypi_mirror=pypi_mirror,
            )
    do_install_dependencies(
        dev=dev,
        requirements=requirements,
        allow_global=allow_global,
        skip_lock=skip_lock,
        concurrent=concurrent,
        requirements_dir=requirements_dir,
        pypi_mirror=pypi_mirror,
    )

    # Hint the user what to do to activate the virtualenv.
    if not allow_global and not deploy and "PIPENV_ACTIVE" not in os.environ:
        click.echo(
            "To activate this project's virtualenv, run {0}.\n"
            "Alternatively, run a command "
            "inside the virtualenv with {1}.".format(
                crayons.red("pipenv shell"), crayons.red("pipenv run")
            )
        )
826660
def virtualenv(self, virtualenv):
        '''
        
        '''
        # If a boolean is passed then set the internal _skip_virtualenv flag
        if isinstance(virtualenv, bool):
            self._skip_virtualenv = virtualenv
        else:
            self._virtualenv = virtualenv
            if not os.path.isdir(self._virtualenv):
                raise Exception("virtualenv %s not found" % self._virtualenv)
            LOG.info("Using existing virtualenv at %s" % self._virtualenv)
            # use supplied virtualenv path
            self._pkg_venv = self._virtualenv
            self._skip_virtualenv = True
1327883
def create_virtualenv(pkg, repo_dest, python):
    """"""
    workon_home = os.environ.get('WORKON_HOME')
    venv_cmd = find_executable('virtualenv')
    python_bin = find_executable(python)
    if not python_bin:
        raise EnvironmentError('%s is not installed or not '
                               'available on your $PATH' % python)
    if workon_home:
        # Can't use mkvirtualenv directly here because relies too much on
        # shell tricks. Simulate it:
        venv = os.path.join(workon_home, pkg)
    else:
        venv = os.path.join(repo_dest, '.virtualenv')
    if venv_cmd:
        if not verbose:
            log.info('Creating virtual environment in %r' % venv)
        args = ['--python', python_bin, venv]
        if not verbose:
            args.insert(0, '-q')
        subprocess.check_call([venv_cmd] + args)
    else:
        raise EnvironmentError('Could not locate the virtualenv. Install with '
                               'pip install virtualenv.')
    return venv
1025765
def project_version(full_version):
    

    project_full_version=full_version
    v = _parse_project_version(full_version)
    name = project_name()
    project_fullname = '-'.join([name,v])

    return _setenv(project_full_version=project_full_version, project_version=v,project_name=name,project_fullname=project_fullname)
118259
def create_new_project(self):
        """"""
        self.switch_to_plugin()
        active_project = self.current_active_project
        dlg = ProjectDialog(self)
        dlg.sig_project_creation_requested.connect(self._create_project)
        dlg.sig_project_creation_requested.connect(self.sig_project_created)
        if dlg.exec_():
            if (active_project is None
                    and self.get_option('visible_if_project_open')):
                self.show_explorer()
            self.sig_pythonpath_changed.emit()
            self.restart_consoles()
423238
def create_vs(self, name, ip, port, protocol, profile, pool_name):
        '''
        
        '''
        vs = self.bigIP.LocalLB.VirtualServer
        vs_def = vs.typefactory.create('Common.VirtualServerDefinition')

        vs_def.name = name
        vs_def.address = ip
        vs_def.port = port

        common_protocols = vs.typefactory.create('Common.ProtocolType')

        p = [i[0] for i in common_protocols if i[0].split('_')[1] == protocol.upper()]

        if p:
            vs_def.protocol = p
        else:
            raise CommandExecutionError('Unknown protocol')

        vs_def_seq = vs.typefactory.create('Common.VirtualServerSequence')
        vs_def_seq.item = [vs_def]

        vs_type = vs.typefactory.create(
            'LocalLB.VirtualServer.VirtualServerType'
        )
        vs_resource = vs.typefactory.create(
            'LocalLB.VirtualServer.VirtualServerResource'
        )

        vs_resource.type = vs_type.RESOURCE_TYPE_POOL
        vs_resource.default_pool_name = pool_name

        resource_seq = vs.typefactory.create(
            'LocalLB.VirtualServer.VirtualServerResourceSequence'
        )

        resource_seq.item = [vs_resource]

        vs_context = vs.typefactory.create('LocalLB.ProfileContextType')
        vs_profile = vs.typefactory.create(
            'LocalLB.VirtualServer.VirtualServerProfile'
        )

        vs_profile.profile_context = vs_context.PROFILE_CONTEXT_TYPE_ALL
        vs_profile.profile_name = protocol

        vs_profile_http = vs.typefactory.create(
            'LocalLB.VirtualServer.VirtualServerProfile'
        )
        vs_profile_http.profile_name = profile

        vs_profile_conn = vs.typefactory.create(
            'LocalLB.VirtualServer.VirtualServerProfile'
        )
        vs_profile_conn.profile_name = 'oneconnect'

        vs_profile_seq = vs.typefactory.create(
            'LocalLB.VirtualServer.VirtualServerProfileSequence'
        )
        vs_profile_seq.item = [vs_profile, vs_profile_http, vs_profile_conn]

        try:
            vs.create(definitions=vs_def_seq,
                      wildmasks=['255.255.255.255'],
                      resources=resource_seq,
                      profiles=[vs_profile_seq])
        except Exception as e:
            raise Exception(
                'Unable to create `{0}` virtual server\n\n{1}'.format(name, e)
            )
        return True
1234312
def new_cmd(argv):
    """"""
    parser = mkvirtualenv_argparser()
    parser.add_argument('-a', dest='project', help='Provide a full path to a \
project directory to associate with the new environment.')

    parser.add_argument('envname')
    args, rest = parser.parse_known_args(argv)
    project = expandpath(args.project) if args.project else None

    mkvirtualenv(args.envname, args.python, args.packages, project,
                 args.requirements, rest)
    if args.activate:
        shell(args.envname)
930457
def create_environment(home_dir, site_packages=True, clear=False,
                       unzip_setuptools=False, use_distribute=False):
    
    home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)

    py_executable = os.path.abspath(install_python(
        home_dir, lib_dir, inc_dir, bin_dir,
        site_packages=site_packages, clear=clear))

    install_distutils(lib_dir, home_dir)

    if use_distribute or os.environ.get('VIRTUALENV_USE_DISTRIBUTE'):
        install_distribute(py_executable, unzip=unzip_setuptools)
    else:
        install_setuptools(py_executable, unzip=unzip_setuptools)

    install_pip(py_executable)

    install_activate(home_dir, bin_dir)
543249
def rmvirtualenv():
    
    path = '/'.join([deployment_root(),'env',env.project_fullname])
    link = '/'.join([deployment_root(),'env',env.project_name])
    if version_state('mkvirtualenv'):
        sudo(' '.join(['rm -rf',path]))
        sudo(' '.join(['rm -f',link]))
        sudo('rm -f /var/local/woven/%s*'% env.project_fullname)
        set_version_state('mkvirtualenv',delete=True)
1324663
def create():
    
    # Generate project locale
    locale = env.locale.replace("UTF-8", "utf8")
    with hide("stdout"):
        if locale not in run("locale -a"):
            sudo("locale-gen %s" % env.locale)
            sudo("update-locale %s" % env.locale)
            sudo("service postgresql restart")
            run("exit")

    # Create project path
    run("mkdir -p %s" % env.proj_path)

    # Set up virtual env
    run("mkdir -p %s" % env.venv_home)
    with cd(env.venv_home):
        if exists(env.proj_name):
            if confirm("Virtualenv already exists in host server: %s"
                       "\nWould you like to replace it?" % env.proj_name):
                run("rm -rf %s" % env.proj_name)
            else:
                abort()
        run("virtualenv %s" % env.proj_name)

    # Upload project files
    if env.deploy_tool in env.vcs_tools:
        vcs_upload()
    else:
        rsync_upload()

    # Create DB and DB user
    pw = db_pass()
    user_sql_args = (env.proj_name, pw.replace("'", "\'"))
    user_sql = "CREATE USER %s WITH ENCRYPTED PASSWORD '%s';" % user_sql_args
    psql(user_sql, show=False)
    shadowed = "*" * len(pw)
    print_command(user_sql.replace("'%s'" % pw, "'%s'" % shadowed))
    psql("CREATE DATABASE %s WITH OWNER %s ENCODING = 'UTF8' "
         "LC_CTYPE = '%s' LC_COLLATE = '%s' TEMPLATE template0;" %
         (env.proj_name, env.proj_name, env.locale, env.locale))

    # Set up SSL certificate
    if not env.ssl_disabled:
        conf_path = "/etc/nginx/conf"
        if not exists(conf_path):
            sudo("mkdir %s" % conf_path)
        with cd(conf_path):
            crt_file = env.proj_name + ".crt"
            key_file = env.proj_name + ".key"
            if not exists(crt_file) and not exists(key_file):
                try:
                    crt_local, = glob(join("deploy", "*.crt"))
                    key_local, = glob(join("deploy", "*.key"))
                except ValueError:
                    parts = (crt_file, key_file, env.domains[0])
                    sudo("openssl req -new -x509 -nodes -out %s -keyout %s "
                         "-subj '/CN=%s' -days 3650" % parts)
                else:
                    upload_template(crt_local, crt_file, use_sudo=True)
                    upload_template(key_local, key_file, use_sudo=True)

    # Install project-specific requirements
    upload_template_and_reload("settings")
    with project():
        if env.reqs_path:
            pip("-r %s/%s" % (env.proj_path, env.reqs_path))
        pip("gunicorn setproctitle psycopg2 "
            "django-compressor python-memcached")
    # Bootstrap the DB
        manage("createdb --noinput --nodata")
        python("from django.conf import settings;"
               "from django.contrib.sites.models import Site;"
               "Site.objects.filter(id=settings.SITE_ID).update(domain='%s');"
               % env.domains[0])
        for domain in env.domains:
            python("from django.contrib.sites.models import Site;"
                   "Site.objects.get_or_create(domain='%s');" % domain)
        if env.admin_pass:
            pw = env.admin_pass
            user_py = ("from django.contrib.auth import get_user_model;"
                       "User = get_user_model();"
                       "u, _ = User.objects.get_or_create(username='admin');"
                       "u.is_staff = u.is_superuser = True;"
                       "u.set_password('%s');"
                       "u.save();" % pw)
            python(user_py, show=False)
            shadowed = "*" * len(pw)
            print_command(user_py.replace("'%s'" % pw, "'%s'" % shadowed))

    return True
416214
def _check_virtualenv():
    
    from os import waitpid
    from subprocess import Popen, PIPE
    penvs = Popen("source /usr/local/bin/virtualenvwrapper.sh; workon",
                 shell=True, executable="/bin/bash", stdout=PIPE, stderr=PIPE)
    waitpid(penvs.pid, 0)
    envs = penvs.stdout.readlines()
    enverr = penvs.stderr.readlines()
    result = (settings.venv + '\n') in envs and len(enverr) == 0

    vms("Find virtualenv: {}".format(' '.join(envs).replace('\n', '')))
    vms("Find virtualenv | stderr: {}".format(' '.join(enverr)))
    
    if not result:
        info(envs)
        err("The virtualenv '{}' does not exist; can't use CI server.".format(settings.venv))
        if len(enverr) > 0:
            map(err, enverr)
    return result
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')))
1162506
def create_CreateProcess(original_name):
    

    def new_CreateProcess(app_name, cmd_line, *args):
        try:
            import _subprocess
        except ImportError:
            import _winapi as _subprocess
        send_process_created_message()
        return getattr(_subprocess, original_name)(app_name, patch_arg_str_win(cmd_line), *args)

    return new_CreateProcess
107139
def get_virtualenv_path(ve_base, ve_name):
    
    if not ve_base:
        raise exceptions.NoVirtualenvsDirectory(
            "could not figure out a virtualenvs directory. "
            "make sure $HOME is set, or $WORKON_HOME,"
            " or set virtualenvs=something in your .vexrc")

    # Using this requires get_ve_base to pass through nonexistent dirs
    if not os.path.exists(ve_base):
        message = (
            "virtualenvs directory {0!r} not found. "
            "Create it or use vex --make to get started."
        ).format(ve_base)
        raise exceptions.NoVirtualenvsDirectory(message)

    if not ve_name:
        raise exceptions.InvalidVirtualenv("no virtualenv name")

    # n.b.: if ve_name is absolute, ve_base is discarded by os.path.join,
    # and an absolute path will be accepted as first arg.
    # So we check if they gave an absolute path as ve_name.
    # But we don't want this error if $PWD == $WORKON_HOME,
    # in which case 'foo' is a valid relative path to virtualenv foo.
    ve_path = os.path.join(ve_base, ve_name)
    if ve_path == ve_name and os.path.basename(ve_name) != ve_name:
        raise exceptions.InvalidVirtualenv(
            'To run in a virtualenv by its path, '
            'use "vex --path {0}"'.format(ve_path))

    ve_path = os.path.abspath(ve_path)
    if not os.path.exists(ve_path):
        raise exceptions.InvalidVirtualenv(
            "no virtualenv found at {0!r}.".format(ve_path))
    return ve_path
131662
def _build_new_virtualenv(self):
        ''''''
        if self._virtualenv is None:
            # virtualenv was "None" which means "do default"
            self._pkg_venv = os.path.join(self._temp_workspace, 'venv')
            self._venv_pip = 'bin/pip'
            if sys.platform == 'win32' or sys.platform == 'cygwin':
                self._venv_pip = 'Scripts\pip.exe'

            python_exe = self._python_executable()

            proc = Popen(["virtualenv", "-p", python_exe,
                          self._pkg_venv], stdout=PIPE, stderr=PIPE)
            stdout, stderr = proc.communicate()
            LOG.debug("Virtualenv stdout: %s" % stdout)
            LOG.debug("Virtualenv stderr: %s" % stderr)

            if proc.returncode is not 0:
                raise Exception('virtualenv returned unsuccessfully')

        else:
            raise Exception('cannot build a new virtualenv when asked to omit')
1159078
def create_new_project(project_name)
      # Check project existence
      (error(_('wizard.project.name_exist')); return false) if project_exists?(Dir.pwd, project_name)
      # Setup the bebox boxes directory
      bebox_boxes_setup
      # Asks to choose an existing box
      current_box = choose_box(get_existing_boxes)
      vagrant_box_base = "#{BEBOX_BOXES_PATH}/#{get_valid_box_uri(current_box)}"
      # Asks user to choose vagrant box provider
      vagrant_box_provider = choose_option(%w{virtualbox vmware}, _('wizard.project.choose_box_provider'))
      # Set default environments
      default_environments = %w{vagrant staging production}
      # Project creation
      project = Bebox::Project.new(project_name, vagrant_box_base, Dir.pwd, vagrant_box_provider, default_environments)
      output = project.create
      ok _('wizard.project.creation_success')%{project_name: project_name}
      return output
    end