Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Reads key-value pairs from a .env file and can set them as environment variables. It helps in developing applications following the 12-factor principles.

License

NotificationsYou must be signed in to change notification settings

theskumar/python-dotenv

Build StatusPyPI version

python-dotenv reads key-value pairs from a.env file and can set them asenvironment variables. It helps in the development of applications following the12-factor principles.

Getting Started

pip install python-dotenv

If your application takes its configuration from environment variables, like a12-factor application, launching it in development is not very practical becauseyou have to set those environment variables yourself.

To help you with that, you can add python-dotenv to your application to make itload the configuration from a.env file when it is present (e.g. indevelopment) while remaining configurable via the environment:

fromdotenvimportload_dotenvload_dotenv()# reads variables from a .env file and sets them in os.environ# 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_dotenv() will:

  • Look for a.env file in the same directory as the Python script (or higher up the directory tree).
  • Read each key-value pair and add it toos.environ.
  • Not override existing environment variables (override=False). Passoverride=True to override existing variables.

To configure the development environment, add a.env in the root directory ofyour project:

.├── .env└── foo.py

The syntax of.env files supported by python-dotenv is similar to that ofBash:

# Development settingsDOMAIN=example.orgADMIN_EMAIL=admin@${DOMAIN}ROOT_URL=${DOMAIN}/app

If you use variables in values, ensure they are surrounded with{ and},like${DOMAIN}, as bare variables such as$DOMAIN are not expanded.

You will probably want to add.env to your.gitignore, especially if itcontains secrets like a password.

See the section "File format" below for more information about what you can write in a.env file.

Other Use Cases

Load configuration without altering the environment

The functiondotenv_values works more or less the same way asload_dotenv,except it doesn't touch the environment, it just returns adict with thevalues parsed from the.env file.

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 stream

load_dotenv anddotenv_values acceptstreams via theirstream argument. It is thus possible to load the variables from sources otherthan the filesystem (e.g. the network).

fromioimportStringIOfromdotenvimportload_dotenvconfig=StringIO("USER=foo\nEMAIL=foo@example.org")load_dotenv(stream=config)

Load .env files in IPython

You can use dotenv in IPython. By default, it will usefind_dotenv to search for a.env file:

%load_extdotenv%dotenv

You can also specify a path:

%dotenvrelative/or/absolute/path/to/.env

Optional flags:

  • -o to override existing variables.
  • -v for increased verbosity.

Disable load_dotenv

SetPYTHON_DOTENV_DISABLED=1 to disableload_dotenv() from loading .envfiles or streams. Useful when you can't modify third-party package calls or inproduction.

Command-line Interface

A CLI interfacedotenv is also included, which helps you manipulate the.envfile without manually opening it.

$ pip install"python-dotenv[cli]"$ dotenvset USER foo$ dotenvset EMAIL foo@example.org$ dotenv listUSER=fooEMAIL=foo@example.org$ dotenv list --format=json{"USER":"foo","EMAIL":"foo@example.org"}$ dotenv run -- python foo.py

Rundotenv --help for more information about the options and subcommands.

File format

The format is not formally specified and still improves over time. That beingsaid,.env files should mostly look like Bash files. Reading from FIFOs (namedpipes) on Unix systems is also supported.

Keys can be unquoted or single-quoted. Values can be unquoted, single- ordouble-quoted. Spaces before and after keys, equal signs, and values areignored. 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,\v

Multiline values

It is possible for single- or double-quoted values to span multiple lines. Thefollowing examples are equivalent:

FOO="first linesecond line"
FOO="first line\nsecond line"

Variable without a value

A variable can have no value:

FOO

It results indotenv_values associating that variable name with the valueNone (e.g.{"FOO": None}.load_dotenv, on the other hand, simply ignoressuch variables.

This shouldn't be confused withFOO=, in which case the variable is associatedwith the empty string.

Variable expansion

python-dotenv can interpolate variables using POSIX variable expansion.

Withload_dotenv(override=True) ordotenv_values(), the value of a variableis the first of the values defined in the following list:

  • Value of that variable in the.env file.
  • 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 thevalues defined in the following list:

  • Value of that variable in the environment.
  • Value of that variable in the.env file.
  • Default value, if provided.
  • Empty string.

Related Projects

Acknowledgements

This project is currently maintained bySaurabh Kumar andBertrand Bonnefoy-Claudet and would not have been possible withoutthe support of theseawesome people.

About

Reads key-value pairs from a .env file and can set them as environment variables. It helps in developing applications following the 12-factor principles.

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks


[8]ページ先頭

©2009-2026 Movatter.jp