Prepares current environment and returns Python binary name.

        This adds some virtualenv friendliness so that we try use uwsgi from it.

        :rtype: str|unicode
774463
def prepare_env(cls):
        
        os.environ['PATH'] = cls.get_env_path()
        return os.path.basename(Finder.python())
210903
def do_create_virtualenv(python=None, site_packages=False, pypi_mirror=None):
    """"""

    click.echo(
        crayons.normal(fix_utf8("Creating a virtualenv for this project…"), bold=True), err=True
    )
    click.echo(
        u"Pipfile: {0}".format(crayons.red(project.pipfile_location, bold=True)),
        err=True,
    )

    # Default to using sys.executable, if Python wasn't provided.
    if not python:
        python = sys.executable
    click.echo(
        u"{0} {1} {3} {2}".format(
            crayons.normal("Using", bold=True),
            crayons.red(python, bold=True),
            crayons.normal(fix_utf8("to create virtualenv…"), bold=True),
            crayons.green("({0})".format(python_version(python))),
        ),
        err=True,
    )

    cmd = [
        vistir.compat.Path(sys.executable).absolute().as_posix(),
        "-m",
        "virtualenv",
        "--prompt=({0}) ".format(project.name),
        "--python={0}".format(python),
        project.get_location_for_virtualenv(),
    ]

    # Pass site-packages flag to virtualenv, if desired…
    if site_packages:
        click.echo(
            crayons.normal(fix_utf8("Making site-packages available…"), bold=True), err=True
        )
        cmd.append("--system-site-packages")

    if pypi_mirror:
        pip_config = {"PIP_INDEX_URL": vistir.misc.fs_str(pypi_mirror)}
    else:
        pip_config = {}

    # Actually create the virtualenv.
    nospin = environments.PIPENV_NOSPIN
    with create_spinner("Creating virtual environment...") as sp:
        c = vistir.misc.run(
            cmd, verbose=False, return_object=True, write_to_stdout=False,
            combine_stderr=False, block=True, nospin=True, env=pip_config,
        )
        click.echo(crayons.blue("{0}".format(c.out)), err=True)
        if c.returncode != 0:
            sp.fail(environments.PIPENV_SPINNER_FAIL_TEXT.format("Failed creating virtual environment"))
            error = c.err if environments.is_verbose() else exceptions.prettify_exc(c.err)
            raise exceptions.VirtualenvCreationException(
                extra=[crayons.red("{0}".format(error)),]
            )
        else:

            sp.green.ok(environments.PIPENV_SPINNER_OK_TEXT.format(u"Successfully created virtual environment!"))

    # Associate project directory with the environment.
    # This mimics Pew's "setproject".
    project_file_name = os.path.join(project.virtualenv_location, ".project")
    with open(project_file_name, "w") as f:
        f.write(vistir.misc.fs_str(project.project_directory))
    from .environment import Environment
    sources = project.pipfile_sources
    project._environment = Environment(
        prefix=project.get_location_for_virtualenv(),
        is_venv=True,
        sources=sources,
        pipfile=project.parsed_pipfile,
        project=project
    )
    project._environment.add_dist("pipenv")
    # Say where the virtualenv is.
    do_where(virtualenv=True, bare=False)
614521
def get_from_env():
    
    type_env = os.getenv(OC_RESOURCE_TYPE)
    if type_env is None:
        return None
    type_env = type_env.strip()

    labels_env = os.getenv(OC_RESOURCE_LABELS)
    if labels_env is None:
        return Resource(type_env)

    labels = parse_labels(labels_env)

    return Resource(type_env, labels)
1132819
def name(self):
        
        name = self._name.rstrip('/')
        if self._bytes_path:
            name = fsencode(name)
        return name
1345308
def _build_wsgi_env(event, app_name):
    
    gateway = event['parameters']['gateway']
    request = event['parameters']['request']
    ctx = event['rawContext']
    headers = request['header']
    body = six.text_type(json.dumps(request['body']))

    # Render the path correctly so connexion/flask will pass the path params to
    # the handler function correctly.
    # Basically, this replaces "/foo/{param1}/bar/{param2}" with
    # "/foo/123/bar/456".
    path = gateway['resource-path'].format(
        **event['parameters']['request']['path']
    )
    environ = {
        'PATH_INFO': path,
        'QUERY_STRING': urlencode(request['querystring']),
        'REMOTE_ADDR': ctx['identity']['sourceIp'],
        'REQUEST_METHOD': ctx['httpMethod'],
        'SCRIPT_NAME': app_name,
        'SERVER_NAME': app_name,
        'SERVER_PORT': headers.get('X-Forwarded-Port', '80'),
        'SERVER_PROTOCOL': 'HTTP/1.1',
        'wsgi.version': (1, 0),
        'wsgi.url_scheme': headers.get('X-Forwarded-Proto', 'http'),
        'wsgi.input': StringIO(body),
        'wsgi.errors': StringIO(),
        'wsgi.multiprocess': False,
        'wsgi.multithread': False,
        'wsgi.run_once': False,
        'CONTENT_TYPE': headers.get('Content-Type', 'application/json'),
    }
    if ctx['httpMethod'] in ['POST', 'PUT', 'PATCH']:
        environ['CONTENT_LENGTH'] = str(len(body))

    for header_name, header_value in headers.items():
        wsgi_name = 'HTTP_{}'.format(header_name.upper().replace('-', '_'))
        environ[wsgi_name] = str(header_value)

    return environ
899625
def getenv(option_name, default=None):
    """"""
    env = "%s_%s" % (NAMESPACE.upper(), option_name.upper())
    return os.environ.get(env, default)
358552
def get_environ(self, sock):
        """"""
        cipher = sock.cipher()
        ssl_environ = {
            "wsgi.url_scheme": "https",
            "HTTPS": "on",
            'SSL_PROTOCOL': cipher[1],
            'SSL_CIPHER': cipher[0]
##            SSL_VERSION_INTERFACE 	string 	The mod_ssl program version
##            SSL_VERSION_LIBRARY 	string 	The OpenSSL program version
            }
        return ssl_environ
1285395
def create_virtualenv(self):
        
        return task.create_virtualenv(self.target, self.datadir,
            self._preload_image(), self._get_container_name)
679946
def _stdlib_paths():
    
    attr_candidates = [
        'prefix',
        'real_prefix',  # virtualenv: only set inside a virtual environment.
        'base_prefix',  # venv: always set, equal to prefix if outside.
    ]
    prefixes = (getattr(sys, a) for a in attr_candidates if hasattr(sys, a))
    version = 'python%s.%s' % sys.version_info[0:2]
    return set(os.path.abspath(os.path.join(p, 'lib', version))
               for p in prefixes)
517483
def get_environment(self):
        '''
        
        '''
        env = {}
        if self.http:
            env['http_proxy'] = env['HTTP_PROXY'] = self.http
        if self.https:
            env['https_proxy'] = env['HTTPS_PROXY'] = self.https
        if self.ftp:
            env['ftp_proxy'] = env['FTP_PROXY'] = self.ftp
        if self.no_proxy:
            env['no_proxy'] = env['NO_PROXY'] = self.no_proxy
        return env
70219
def get_env():
    
    if not __ENV__:
        env = os.environ["env"] if "env" in os.environ else "Dev"
        set_env(env)
    return __ENV__
1058819
def substitute_environ(self):
        
        for attr_name in dir(self):
            if attr_name.startswith('_') or attr_name.upper() != attr_name:
                continue

            orig_value = getattr(self, attr_name)
            is_required = isinstance(orig_value, Required)
            orig_type = orig_value.v_type if is_required else type(orig_value)
            env_var_name = self._ENV_PREFIX + attr_name
            env_var = os.getenv(env_var_name, None)
            if env_var is not None:
                if issubclass(orig_type, bool):
                    env_var = env_var.upper() in ('1', 'TRUE')
                elif issubclass(orig_type, int):
                    env_var = int(env_var)
                elif issubclass(orig_type, Path):
                    env_var = Path(env_var)
                elif issubclass(orig_type, bytes):
                    env_var = env_var.encode()
                # could do floats here and lists etc via json
                setattr(self, attr_name, env_var)
            elif is_required and attr_name not in self._custom_settings:
                raise RuntimeError('The required environment variable "{0}" is currently not set, '
                                   'you\'ll need to run `source activate.settings.sh` '
                                   'or you can set that single environment variable with '
                                   '`export {0}="<value>"`'.format(env_var_name))
279510
def get_version(self, as_tuple=False):
        
        if as_tuple:
            return uwsgi.version_info

        return decode(uwsgi.version)
1015799
def _virtualenv_sys(venv_path):
    ""
    executable = os.path.join(venv_path, env_bin_dir, 'python')
    # Must use "executable" as the first argument rather than as the
    # keyword argument "executable" to get correct value from sys.path
    p = subprocess.Popen([executable,
        '-c', 'import sys;'
              'print (sys.version[:3]);'
              'print ("\\n".join(sys.path));'],
        env={},
        stdout=subprocess.PIPE)
    stdout, err = p.communicate()
    assert not p.returncode and stdout
    lines = stdout.decode('utf-8').splitlines()
    return lines[0], list(filter(bool, lines[1:]))
293725
def setup_environ(self):
        
        SimpleHandler.setup_environ(self)
        self.environ['ws4py.socket'] = get_connection(self.environ['wsgi.input'])
        self.http_version = self.environ['SERVER_PROTOCOL'].rsplit('/')[-1]
1273276
def training_env():  # type: () -> _env.TrainingEnv
    

    from sagemaker_containers import _env

    return _env.TrainingEnv(
        resource_config=_env.read_resource_config(),
        input_data_config=_env.read_input_data_config(),
        hyperparameters=_env.read_hyperparameters())
143931
def prepare_environment(default_settings=_default_settings, **kwargs):
    # pylint: disable=unused-argument
    '''
    
    '''
    for key, value in default_settings.items():
        os.environ.setdefault(key, value)
    os.environ.update(kwargs)
    if six.PY2:  # nocv
        warnings.warn(
            'Python 2.7 is deprecated and will dropped in 2.0, use Python >3.5',
            DeprecationWarning
        )