Package: python-dotenv-yaml
python-dotenvPython-dotenv reads key-value pairs from a.envfile and can set them as environment
variables. It helps in the development of applications following the12-factorprinciples.Getting StartedOther Use CasesLoad configuration without altering the environmentParse configuration as a streamLoad .env files in IPythonCommand-line InterfaceFile formatMultiline valuesVariable expansionRelated ProjectsAcknowledgementsGetting Startedpipinstallpython-dotenvIf your application takes its configuration from environment variables, like a 12-factor
application, launching it in development is not very practical because you have to set
those environment variables yourself.To help you with that, you can add Python-dotenv to your application to make it load the
configuration from a.envfile when it is present (e.g. in development) while remaining
configurable via the environment:fromdotenvimportload_dotenvload_dotenv()# take environment variables from .env.# Code of your application, which uses environment variables (e.g. from `os.environ` or# `os.getenv`) as if they came from the actual environment.By default,load_dotenvdoesn't override existing environment variables.To configure the development environment, add a.envin the root directory of your
project:.
├── .env
└── foo.pyThe syntax of.envfiles supported by python-dotenv is similar to that of Bash:# Development settingsDOMAIN=example.orgADMIN_EMAIL=admin@${DOMAIN}ROOT_URL=${DOMAIN}/appIf you use variables in values, ensure they are surrounded with{and}, like${DOMAIN}, as bare variables such as$DOMAINare not expanded.You will probably want to add.envto your.gitignore, especially if it contains
secrets like a password.See the section "File format" below for more information about what you can write in a.envfile.Other Use CasesLoad configuration without altering the environmentThe functiondotenv_valuesworks more or less the same way asload_dotenv, except it
doesn't touch the environment, it just returns adictwith the values parsed from the.envfile.fromdotenvimportdotenv_valuesconfig=dotenv_values(".env")# config = {"USER": "foo", "EMAIL": "foo@example.org"}This notably enables advanced configuration management:importosfromdotenvimportdotenv_valuesconfig={**dotenv_values(".env.shared"),# load shared development variables**dotenv_values(".env.secret"),# load sensitive variables**os.environ,# override loaded values with environment variables}Parse configuration as a streamload_dotenvanddotenv_valuesacceptstreamsvia theirstreamargument.  It is thus possible to load the variables from sources other than the
filesystem (e.g. the network).fromioimportStringIOfromdotenvimportload_dotenvconfig=StringIO("USER=foo\nEMAIL=foo@example.org")load_dotenv(stream=config)Load .env files in IPythonYou can use dotenv in IPython.  By default, it will usefind_dotenvto search for a.envfile:%load_extdotenv%dotenvYou can also specify a path:%dotenvrelative/or/absolute/path/to/.envOptional flags:-oto override existing variables.-vfor increased verbosity.Command-line InterfaceA CLI interfacedotenvis also included, which helps you manipulate the.envfile
without manually opening it.$pipinstall"python-dotenv[cli]"$dotenvsetUSER=foo
$dotenvsetEMAIL=foo@example.org
$dotenvlistUSER=fooEMAIL=foo@example.org
$dotenvrun--pythonfoo.pyRundotenv --helpfor more information about the options and subcommands.File formatThe format is not formally specified and still improves over time.  That being said,.envfiles should mostly look like Bash files.Keys can be unquoted or single-quoted. Values can be unquoted, single- or double-quoted.
Spaces before and after keys, equal signs, and values are ignored. Values can be followed
by a comment.  Lines can start with theexportdirective, which has no effect on their
interpretation.Allowed escape sequences:in single-quoted values:\\,\'in double-quoted values:\\,\',\",\a,\b,\f,\n,\r,\t,\vMultiline valuesIt is possible for single- or double-quoted values to span multiple lines.  The following
examples are equivalent:FOO="first linesecond line"FOO="first line\nsecond line"Variable expansionPython-dotenv can interpolate variables using POSIX variable expansion.Withload_dotenv(override=True)ordotenv_values(), the value of a variable is the
first of the values defined in the following list:Value of that variable in the.envfile.Value of that variable in the environment.Default value, if provided.Empty string.Withload_dotenv(override=False), the value of a variable is the first of the values
defined in the following list:Value of that variable in the environment.Value of that variable in the.envfile.Default value, if provided.Empty string.Related ProjectsHoncho- For managing
Procfile-based applications.django-dotenvdjango-environdjango-configurationdump-envenvironsdynaconfAcknowledgementsThis project is currently maintained bySaurabh KumarandBertrand Bonnefoy-Claudetand would not have been possible
without the support of theseawesome
people.ChangelogAll notable changes to this project will be documented in this file.The format is based onKeep a Changelog, and this
project adheres toSemantic Versioning.0.17.1- 2021-04-29FixedFixed tests for build environments relying onPYTHONPATH(#318 by@befeleme).0.17.0- 2021-04-02ChangedMakedotenv get <key>only show the value, notkey=value(#313 by@bbc2).AddedAdd--override/--no-overrideoption todotenv run(#312 by@zueveand@bbc2).0.16.0- 2021-03-27ChangedThe default value of theencodingparameter forload_dotenvanddotenv_valuesis
now"utf-8"instead ofNone(#306 by@bbc2).Fix resolution order in variable expansion withoverride=False(#287 by@bbc2).0.15.0- 2020-10-28AddedAdd--exportoption tosetto make it prepend the binding withexport(#270 by@jadutter).ChangedMakesetcommand create the.envfile in the current directory if no.envfile was
found (#270 by@jadutter).FixedFix potentially empty expanded value for duplicate key (#260 by@bbc2).Fix import error on Python 3.5.0 and 3.5.1 (#267 by@gongqingkui).Fix parsing of unquoted values containing several adjacent space or tab characters
(#277 by@bbc2, review by@x-yuri).0.14.0- 2020-07-03ChangedPrivilege definition in file over the environment in variable expansion (#256 by@elbehery95).FixedImprove error message for when file isn't found (#245 by@snobu).Use HTTPS URL in package meta data (#251 by@ekohl).0.13.0- 2020-04-16AddedAdd support for a Bash-like default value in variable expansion (#248 by@bbc2).0.12.0- 2020-02-28ChangedUse current working directory to find.envwhen bundled by PyInstaller (#213 by@gergelyk).FixedFix escaping of quoted values written byset_key(#236 by@bbc2).Fixdotenv runcrashing on environment variables without values (#237 by@yannham).Remove warning when last line is empty (#238 by@bbc2).0.11.0- 2020-02-07AddedAddinterpolateargument toload_dotenvanddotenv_valuesto disable interpolation
(#232 by@ulyssessouza).ChangedUse logging instead of warnings (#231 by@bbc2).FixedFix installation in non-UTF-8 environments (#225 by@altendky).Fix PyPI classifiers (#228 by@bbc2).0.10.5- 2020-01-19FixedFix handling of malformed lines and lines without a value (#222 by@bbc2):Don't print warning when key has no value.Reject more malformed lines (e.g. "A: B", "a='b',c").Fix handling of lines with just a comment (#224 by@bbc2).0.10.4- 2020-01-17AddedMake typing optional (#179 by@techalchemy).Print a warning on malformed line (#211 by@bbc2).Support keys without a value (#220 by@ulyssessouza).0.10.3Improve interactive mode detection (@andrewsmith)(#183).Refactor parser to fix parsing inconsistencies (@bbc2)(#170).Interpret escapes as control characters only in double-quoted strings.Interpret#as start of comment only if preceded by whitespace.0.10.2Add type hints and expose them to users (@qnighy)(#172)load_dotenvanddotenv_valuesnow accept anencodingparameter, defaults toNone(@theskumar)(@earlbread)([#161])Fixstr/unicodeinconsistency in Python 2: values are alwaysstrnow. (@bbc2)(#121)Fix Unicode error in Python 2, introduced in 0.10.0. (@bbc2)(#176)0.10.1Fix parsing of variable without a value (@asyncee)(@bbc2)(#158)0.10.0Add support for UTF-8 in unquoted values (@bbc2)(#148)Add support for trailing comments (@bbc2)(#148)Add backslashes support in values (@bbc2)(#148)Add support for newlines in values (@bbc2)(#148)Force environment variables to str with Python2 on Windows (@greyli)Drop Python 3.3 support (@greyli)Fix stderr/-out/-in redirection (@venthur)0.9.0Add--versionparameter to cli (@venthur)Enable loading from current directory (@cjauvin)Add 'dotenv run' command for calling arbitrary shell script with .env (@venthur)0.8.1Add tests for docs (@Flimm)Make 'cli' support optional. Usepip install python-dotenv[cli]. (@theskumar)0.8.0set_keyandunset_keyonly modified the affected file instead of
parsing and re-writing file, this causes comments and other file
entact as it is.Add support forexportprefix in the line.Internal refractoring (@theskumar)Allowload_dotenvanddotenv_valuesto work withStringIO())(@alanjds)(@theskumar)(#78)0.7.1Remove hard dependency on iPython (@theskumar)0.7.0Add support to override system environment variable via .env.
(@milonimrod)
(#63)Disable ".env not found" warning by default
(@maxkoryukov)
(#57)0.6.5Add support for special characters\.
(@pjona)
(#60)0.6.4Fix issue with single quotes (@Flimm)
(#52)0.6.3Handle unicode exception in setup.py
(#46)0.6.2Fix dotenv list command (@ticosax)Add iPython Suport
(@tillahoffmann)0.6.0Drop support for Python 2.6Handle escaped charaters and newlines in quoted values. (Thanks@iameugenejo)Remove any spaces around unquoted key/value. (Thanks@paulochf)Added POSIX variable expansion. (Thanks@hugochinchilla)0.5.1Fix find_dotenv - it now start search from the file where this
function is called from.0.5.0Addfind_dotenvmethod that will try to find a.envfile.
(Thanks@isms)0.4.0cli: Added-q/--quoteoption to control the behaviour of quotes
around values in.env. (Thanks@hugochinchilla).Improved test coverage.