Writes dotenv_as_dict to dotenv_path, flattening the values
    :param dotenv_path: .env path
    :param dotenv_as_dict: dict
    :param quote_mode:
    :return:
774281
def flatten_and_write(dotenv_path, dotenv_as_dict, quote_mode='always'):
    
    with open(dotenv_path, 'w') as f:
        for k, v in dotenv_as_dict.items():
            str_format = _get_format(v, quote_mode)
            f.write(str_format.format(key=k, value=v))
    return True
1313865
def write_dict_to_file(file_path, obj):
    
    lines = []
    for key, value in obj.items():
        lines.append(key + ':' + repr(value) + '\n')

    with open(file_path, 'w+') as file:
        file.writelines(lines)

    return None
406124
def environment_as(**kwargs):
  
  new_environment = kwargs
  old_environment = {}

  def setenv(key, val):
    if val is not None:
      os.environ[key] = val if PY3 else _os_encode(val)
    else:
      if key in os.environ:
        del os.environ[key]

  for key, val in new_environment.items():
    old_environment[key] = os.environ.get(key)
    setenv(key, val)
  try:
    yield
  finally:
    for key, val in old_environment.items():
      setenv(key, val)
1003755
def write_dict_to_yaml(dictionary, path, **kwargs):
    
    with open(path, 'w') as f:
        yaml.dump(dictionary, f, indent=4, **kwargs)
699031
def addEnvPath(env, name, value):
    
    try:
        oldval = env[name]
        if not oldval.endswith(';'):
            oldval = oldval + ';'
    except KeyError:
        oldval = ""
    if not value.endswith(';'):
        value = value + ';'
    env[name] = oldval + value
353106
def env(var_name, default=False):
    
    try:
        value = os.environ[var_name]
        if str(value).strip().lower() in ['false', 'f', 'no', 'off' '0', 'none', 'null', '', ]:
            return None
        return value
    except:
        from traceback import format_exc
        msg = "Unable to find the %s environment variable.\nUsing the value %s (the default) instead.\n" % (var_name, default)
        sys.stderr.write(format_exc())
        sys.stderr.write(msg)
        return default
870251
def write(self, presets_path):
        
        if self.builtin:
            raise TypeError("Cannot write built-in preset")

        # Make dictionaries of PresetDefaults values
        odict = self.opts.dict()
        pdict = {self.name: {DESC: self.desc, NOTE: self.note, OPTS: odict}}

        if not os.path.exists(presets_path):
            os.makedirs(presets_path, mode=0o755)

        with open(os.path.join(presets_path, self.name), "w") as pfile:
            json.dump(pdict, pfile)
31890
def write(settings_path, settings_data, merge=True):
    
    settings_path = Path(settings_path)
    if settings_path.exists() and merge:  # pragma: no cover
        with io.open(
            str(settings_path), encoding=default_settings.ENCODING_FOR_DYNACONF
        ) as open_file:
            object_merge(yaml.full_load(open_file), settings_data)

    with io.open(
        str(settings_path),
        "w",
        encoding=default_settings.ENCODING_FOR_DYNACONF,
    ) as open_file:
        yaml.dump(settings_data, open_file)
807234
def set_as_environment_variables(self, override=False):
        
        for k, v in self.dict().items():
            if k in os.environ and not override:
                continue
            # With Python2 on Windows, force environment variables to str to avoid
            # "TypeError: environment can only contain strings" in Python's subprocess.py.
            if PY2 and WIN:
                if isinstance(k, text_type) or isinstance(v, text_type):
                    k = k.encode('ascii')
                    v = v.encode('ascii')
            os.environ[k] = v

        return True
1241793
def _build_env(venv_dir):
    
    # NB: We had to create the because the venv modules wasn't doing what we
    # needed. In particular, if we used it create a venv from an existing venv,
    # it *always* created symlinks back to the original venv's python
    # executables. Then, when you used those linked executables, you ended up
    # interacting with the original venv. I could find no way around this, hence
    # this function.
    prefix = getattr(sys, 'real_prefix', sys.prefix)
    python = Path(prefix) / 'bin' / 'python'
    command = '{} -m venv {}'.format(python, venv_dir)
    try:
        log.info('Creating virtual environment: %s', command)
        subprocess.run(command.split(),
                       stdout=subprocess.PIPE,
                       stderr=subprocess.STDOUT,
                       check=True)
    except subprocess.CalledProcessError as exc:
        log.error("Error creating virtual environment: %s", exc.output)
        raise
843176
def create_jinja_env(template_path):
    
    jinja_env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(template_path),
        block_start_string='{%',
        block_end_string='%}',
        variable_start_string='${',
        variable_end_string='}',
        comment_start_string='{#',
        comment_end_string='#}',
        line_statement_prefix=None,
        line_comment_prefix=None,
        trim_blocks=True,
        lstrip_blocks=True,
        newline_sequence='\n'
    )
    jinja_env.filters['regexreplace'] = regex_replace
    jinja_env.globals.update(uuidgen=uuidgen)
    return jinja_env
721585
def _flatten_from_root(self, env):
        

        nodes = env.components

        # Path through the znode graph from root ('') to env
        path = [nodes[:n] for n in xrange(len(nodes) + 1)]

        # Expand path and map it to the root
        path = map(
            self._get_env_path,
            [Env('/'.join(p)) for p in path]
        )

        data = {}
        for n in path:
            _, config = self._get(n)
            data.update(config)

        return data
6345
def envvar_profile(
    profile_root: str,
    profile_properties: typing.Dict[str, typing.Optional[str]] = None,
    **profile_properties_as_kwargs,
) -> EnvvarProfile:
    
    if profile_properties:
        profile_properties_as_kwargs.update(profile_properties)
    return type(f"{profile_root}Profile", (EnvvarProfile,), {
        "profile_root": profile_root.lower(),
        "profile_properties": list(profile_properties_as_kwargs.keys()),
        **{
            k: EnvvarProfileProperty(name=k, default=v, type_=str)
            for k, v in profile_properties_as_kwargs.items()
        },
    })()
1053609
def save(filepath=None, **kwargs):
    
    if filepath is None:
        filepath = os.path.join('.env')

    with open(filepath, 'wb') as file_handle:
        file_handle.writelines(
            '{0}={1}\n'.format(key.upper(), val)
            for key, val in kwargs.items()
        )
385793
def find_dotenv(filename='.env', raise_error_if_not_found=False, usecwd=False):
    
    if usecwd or '__file__' not in globals():
        # should work without __file__, e.g. in REPL or IPython notebook
        path = os.getcwd()
    else:
        # will work for .py files
        frame_filename = sys._getframe().f_back.f_code.co_filename
        path = os.path.dirname(os.path.abspath(frame_filename))

    for dirname in _walk_to_root(path):
        check_path = os.path.join(dirname, filename)
        if os.path.exists(check_path):
            return check_path

    if raise_error_if_not_found:
        raise IOError('File not found')

    return ''
579394
def _get_path(args_path: Optional[str]) -> str:
    
    env_path = os.getenv(PATH_ENVIRONMENT_VARIABLE)
    for path, source in ((args_path, 'arg'),
                         (env_path, 'env')):
        if not path:
            LOG.debug(f"config.load: skipping {source} (path None)")
            continue
        else:
            LOG.debug(f"config.load: using config path {path} from {source}")
            return path
    return DEFAULT_PATH
99914
def save_to_path(path: str, config: Config) -> None:
    
    LOG.debug(f"Saving config to {path}")
    with open(path, 'w') as cf:
        cf.write(json.dumps({k: v for k, v in config._asdict().items()
                             if k != 'path'}))