Package: python-dotenv
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]"$dotenvsetUSERfoo
$dotenvsetEMAILfoo@example.org
$dotenvlistUSER=fooEMAIL=foo@example.org
$dotenvlist--format=json{"USER":"foo","EMAIL":"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 does not affect 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 without a valueA variable can have no value:FOOIt results indotenv_valuesassociating that variable name with the valueNone(e.g.{"FOO": None}.load_dotenv, on the other hand, simply ignores such variables.This shouldn't be confused withFOO=, in which case the variable is associated with the
empty string.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-environ-2django-configurationdump-envenvironsdynaconfparse_itpython-decoupleAcknowledgementsThis 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.1.0.1- 2024-01-23FixedGracefully handle code which has been imported from a zipfile (#456by@samwyma)Allow modules using load_dotenv to be reloaded when launched in a separate thread ([#497] by@freddyaboulton)Fix file not closed after deletion, handle error in the rewrite function (#469by@Qwerty-133)MiscUse pathlib.Path in tests (#466by@eumiro)Fix year in release date in changelog.md (#454by@jankislinger)Use https in README links (#474by@Nicals)1.0.0- 2023-02-24FixedDrop support for python 3.7, add python 3.12-dev (#449 by@theskumar)Handle situations where the cwd does not exist. (#446 by@jctanner)0.21.1- 2023-01-21AddedUse Python 3.11 non-beta in CI (#438 by@bbc2)Modernize variables code (#434 by@Nougat-Waffle)Modernize main.py and parser.py code (#435 by@Nougat-Waffle)Improve conciseness of cli.py andinit.py (#439 by@Nougat-Waffle)Improve error message forgetandlistcommands when env file can't be opened (#441 by@bbc2)Updated License to align with BSD OSI template (#433 by@lsmith77)FixedFix Out-of-scope error when "dest" variable is undefined (#413 by@theGOTOguy)Fix IPython test warning about deprecatedmagic(#440 by@bbc2)Fix type hint for dotenv_path var, add StrPath alias (#432 by@eaf)0.21.0- 2022-09-03AddedCLI: add support for invocations via 'python -m'. (#395 by@theskumar)load_dotenvfunction now returnsFalse. (#388 by@larsks)CLI: add --format= option to list command. (#407 by@sammck)FixedDrop Python 3.5 and 3.6 and upgrade GA (#393 by@eggplants)Useopeninstead ofio.open. (#389 by@rabinadk1)Improve documentation for variables without a value (#390 by@bbc2)Addparse_itto Related Projects (#410 by@naorlivne)Update README.md (#415 by@harveer07)Improve documentation with direct use of MkDocs (#398 by@bbc2)0.20.0- 2022-03-24AddedAddencoding(Optional[str]) parameter toget_key,set_keyandunset_key.
(#379 by@bbc2)FixedUse dict to specify theentry_pointsparameter ofsetuptools.setup(#376 by@mgorny).Don't build universal wheels (#387 by@bbc2).0.19.2- 2021-11-11FixedInset_key, add missing newline character before new entry if necessary. (#361 by@bbc2)0.19.1- 2021-08-09AddedAdd support for Python 3.10. (#359 by@theskumar)0.19.0- 2021-07-24ChangedRequire Python 3.5 or a later version.  Python 2 and 3.4 are no longer supported. (#341
by@bbc2).AddedThedotenv_pathargument ofset_keyandunset_keynow has a type ofUnion[str, os.PathLike]instead of justos.PathLike(#347 by@bbc2).Thestreamargument ofload_dotenvanddotenv_valuescan now be a text stream
(IO[str]), which includes values likeio.StringIO("foo")andopen("file.env", "r")(#348 by@bbc2).0.18.0- 2021-06-20ChangedRaiseValueErrorifquote_modeisn't one ofalways,autoorneverinset_key(#330 by@bbc2).When writing a value to a .env file withset_keyordotenv set <key> <value>(#330
by@bbc2):Use single quotes instead of double quotes.Don't strip surrounding quotes.Inautomode, don't add quotes if the value is only made of alphanumeric characters
(as determined bystring.isalnum).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 Support
(@tillahoffmann)0.6.0Drop support for Python 2.6Handle escaped characters 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.