Giter Site home page Giter Site logo

theskumar / python-dotenv Goto Github PK

View Code? Open in Web Editor NEW
7.1K 34.0 405.0 713 KB

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.

Home Page: https://saurabh-kumar.com/python-dotenv/

License: BSD 3-Clause "New" or "Revised" License

Python 98.93% Makefile 1.07%
python devops-tools dotenv 12-factor-app configuration env environment-variables

python-dotenv's Introduction

python-dotenv

Build Status PyPI version

Python-dotenv reads key-value pairs from a .env file and can set them as environment variables. It helps in the development of applications following the 12-factor principles.

Getting Started

pip install python-dotenv

If 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 .env file when it is present (e.g. in development) while remaining configurable via the environment:

from dotenv import load_dotenv

load_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_dotenv doesn't override existing environment variables.

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

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

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

# Development settings
DOMAIN=example.org
ADMIN_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 it contains 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 function dotenv_values works more or less the same way as load_dotenv, except it doesn't touch the environment, it just returns a dict with the values parsed from the .env file.

from dotenv import dotenv_values

config = dotenv_values(".env")  # config = {"USER": "foo", "EMAIL": "[email protected]"}

This notably enables advanced configuration management:

import os
from dotenv import dotenv_values

config = {
    **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 and dotenv_values accept streams via their stream argument. It is thus possible to load the variables from sources other than the filesystem (e.g. the network).

from io import StringIO

from dotenv import load_dotenv

config = StringIO("USER=foo\n[email protected]")
load_dotenv(stream=config)

Load .env files in IPython

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

%load_ext dotenv
%dotenv

You can also specify a path:

%dotenv relative/or/absolute/path/to/.env

Optional flags:

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

Command-line Interface

A CLI interface dotenv is also included, which helps you manipulate the .env file without manually opening it.

$ pip install "python-dotenv[cli]"
$ dotenv set USER foo
$ dotenv set EMAIL [email protected]
$ dotenv list
USER=foo
[email protected]
$ dotenv list --format=json
{
  "USER": "foo",
  "EMAIL": "[email protected]"
}
$ dotenv run -- python foo.py

Run dotenv --help for more information about the options and subcommands.

File format

The format is not formally specified and still improves over time. That being said, .env files 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 the export directive, 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. The following examples are equivalent:

FOO="first line
second line"
FOO="first line\nsecond line"

Variable without a value

A variable can have no value:

FOO

It results in dotenv_values associating that variable name with the value None (e.g. {"FOO": None}. load_dotenv, on the other hand, simply ignores such variables.

This shouldn't be confused with FOO=, in which case the variable is associated with the empty string.

Variable expansion

Python-dotenv can interpolate variables using POSIX variable expansion.

With load_dotenv(override=True) or dotenv_values(), the value of a variable is 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.

With load_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 .env file.
  • Default value, if provided.
  • Empty string.

Related Projects

Acknowledgements

This project is currently maintained by Saurabh Kumar and Bertrand Bonnefoy-Claudet and would not have been possible without the support of these awesome people.

python-dotenv's People

Contributors

altendky avatar bbc2 avatar cclauss avatar earlbread avatar flimm avatar greyli avatar jacobian avatar jr-minnaar avatar mgorny avatar milonimrod avatar nougat-waffle avatar paulochf avatar peymanslh avatar philippeluickx avatar pidelport avatar pjona avatar praveensenpai avatar qwerty-133 avatar rabinadk1 avatar sammck avatar samwyma avatar sergeyklay avatar smsearcy avatar tedtieken avatar thedrow avatar thegotoguy avatar theskumar avatar ticosax avatar ulyssessouza avatar venthur avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-dotenv's Issues

Chaining/inheritance/sourcing?

I think it would be handy to provide a way for a .env file to include a "base" file with a bunch of default values, that it can then override. A couple thoughts on how it might work:

  • Use "source", like in bash. Just put this line at the top of .env

source "./defaults.env"

And all the values in defaults.env get set as if they were entered in .env itself, with later entries overriding the earlier ones. You would probably also want an unset keyword to remove inherited values.

That's probably the simplest approach. If you wanted to get fancy, you could make the inheritance explicit. Something like:

base "./defaults.env"

MY_VALUE="xyz"          # Sets this variable, as normal
inherit OTHER_VALUE   # Sets this variable to the value specified in defaults.env. Doesn't set any other values.

In other words, you would have to explicitly list which variables to inherit. You could also have inherit all and unset keywords.

I would probably lean towards the first approach, just for simplicity's sake.
Thoughts? I'd be happy to contribute a patch.

Cannot get multiline strings to work?

According to the documentation TEST="foo\nbar" should produce a multiline environment variable however I cannot get it to work, what am I doing wrong? I have tried every variation I can think of.

.env

TEST1="foo\nbar"
TEST2=foo\nbar
TEST3="foo
bar"
TEST4="foo\\nbar"
TEST5=foo\\nbar
TEST6=foo
bar
TEST7="foo\
bar"
TEST8=foo\
bar

test.py

import os
from os.path import join, dirname
from dotenv import load_dotenv

dotenv_path = join(dirname(__file__), '.env')

load_dotenv(dotenv_path, verbose=True)

tests = (
    (key, value)
    for key, value in os.environ.items()
    if key.startswith('TEST'))

for key, value in tests:
    print(key, value)

output

TEST1 foo\nbar
TEST2 foo\\nbar
TEST3 "foo
TEST4 foo\\nbar
TEST5 foo\\\\nbar
TEST6 foo
TEST7 "foo\\
TEST8 foo\\

Trying with "real" environment variables through bash:

$ export TEST="foo
bar"
$ python -c "import os; print(os.environ['TEST'])"
foo
bar

using
Darwin Kernel Version 15.6.0
Python 3.6.2
python-dotenv==0.7.1

document the format of ".env"

I know it is silly, but got me confused for a minute...
I am used to doing "export VAR=value". So I was wondering which format the vars should be in.
Maybe dropping in a line on the README would help for us confused souls?

SECRET_KEY="your_secret_key"
...

BONUS:
When using django-configurations, prepend all vars with DJANGO_

DJANGO_SECRET_KEY="your_secret_key"

Have load_dotenv return dictionary

I really like that python-dotenv expands the variables based on what is in the dotenv file.
I would like to retrieve those expanded vars.

It would be nice if we could do something like:

# .env
DIR=/home/centos/myapp
LOGS_DIR={DIR}/logs
from dotenv import load_dotenv, find_dotenv
my_env = load_dotenv(find_dotenv())
print my_env['LOGS_DIR']
"/home/centos/myapp/logs"

Of course I could call it like:

import os
print os.environ['LOGS_DIR']

but I would need to know exactly the environment variable names defined in the env file.

missing cli option to run a given commandline

I think it would be neat if the dotenv cli tool had an option to run a given commandline WITH the environment vars sourced from specified file, like a RUNNER.

# using the env command to print out env
echo "foo=bar" > .env
$ dotenv -f .env env 
foo=bar

ImportError: No module named 'IPython'

Since version python-dotenv-0.7.0 (version python-dotenv-0.6.5 worked)

File "/usr/lib/python3.5/site-packages/dotenv/__init__.py", line 3, in <module>
    from .ipython import load_ipython_extension
  File "/usr/lib/python3.5/site-packages/dotenv/ipython.py", line 4, in <module>
    from IPython.core.magic import Magics, magics_class, line_magic
ImportError: No module named 'IPython'

How to get the values as a dictionary

I don't want to load the values into the environment, I just want to parse the .env file and get the values as some Python object. Is that possible?

Profile specific environment variable

This library is awesome and I am planning to use it in my application. I am wondering if I could suggest an enhancement which allows depoyment specific configuration variables using this library.

I am proposing to allow multiple .env files such as

  • .env : default file that contains configuration that is common across different deployment environments
  • .env.stage: contains configuration specific to stage deployment. For ex. URL for stage DB
  • .env.production: contains configuration specific to production deployment. For ex, URL for production DB

This is similar to profile specific configuration that Spring allows. Link here

What do you guys think about it. I am happy to raise a PR for it.

find_dotenv not working in nested directory

I have a .py file in this directory heirarchy:

$ROOT/module/service/service.py

within my service.py, I have the following:

load_dotenv(find_dotenv())

DB_HOST = os.environ.get('DB_HOST', 'localhost')
DB_PORT = os.environ.get('DB_PORT', 27017)
DB_USERNAME = os.environ.get('DB_USERNAME', None)
DB_PASSWORD = os.environ.get('DB_PASSWORD', None)

print(f'DB Host: {DB_HOST}')
print(f'DB Port: {DB_PORT}')
print(f'DB Username: {DB_USERNAME}')
print(f'DB Password: {DB_PASSWORD}')

This prints:

DB Host: localhost
DB Port: 27017
DB Username: None
DB Password: None

If I instead change the first line to:

dotenv_path = os.path.join(os.path.dirname(__file__), '..', '..', '.env')
load_dotenv(dotenv_path)

It works and the printout is as expected. Is this expected behaviour? I figured the find_dotenv() will traverse to the root directory.

Dotenv overrides existing env variables

Common behavior of dotenv packages is not overriding existing environment variables. .env by default. env should not write over existing variables or at least provide an option to avoid overriding:

Examples of the common behavior
Go: https://github.com/joho/godotenv/blob/master/godotenv_test.go#L122
Ruby: https://github.com/bkeepers/dotenv/blob/master/spec/dotenv/environment_spec.rb#L25
Haskell: https://github.com/stackbuilders/dotenv-hs/blob/master/spec/Configuration/DotenvSpec.hs#L21
Clojure: https://github.com/tpope/lein-dotenv/blob/master/test/lein_dotenv/plugin_test.clj#L11

Why does this implementation work differently?

Add a `--version` CLI option as per the POSIX standard

Almost all the CLI tools in the linux/unix world do follow the POSIX standard for the CLI args & options.
And the options like --version to print the version and --help to print out usage/help information are two of the most common options almost every CLI tool has.

I think the dotenv tool needs this --version option too.
Something like this:

$ dotenv --version
dotenv v0.6.4

Can do a PR for this if needed.

Thanks.

Add `load` command to `dotenv` application

It'd be very handy to have a way to load the contents of an .env file into my current environment. I don't think there is a way to do this with the current dotenv application, but it'd be fairly easy to add in, and very useful!

pkg_resources.DistributionNotFound: click>=3.0

Trying to run dotenv list (or any other command), getting this error message

Traceback (most recent call last):
File "/foobar/bin/dotenv", line 5, in
from pkg_resources import load_entry_point
File "/foobar/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2603, in
File "/foobar/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 666, in require
File "/foobar/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 565, in resolve
pkg_resources.DistributionNotFound: click>=3.0

Wrong parsing of env variables in single quotes

I have the following .env file:

DATABASE_URL='postgres://localhost:5432/myapp_development'

When I run dotenv get DATABASE_URL this is what I get:
DATABASE_URL="'postgres://localhost:5432/simulator_development'"

When I try to use this with dj-database-url it is failing to parse the DATABASE_URL environment variable as it is.
It seems using single quotes in the .env file is causing this.

It would be nice if this were documented somewhere if the behavior is intended
I spent quite a bit of time trying to figure out where the error was.
Thanks 😃

Boolean field

Is that is possible to define boolean field in .env file using python-dotenv?

`dotenv set` cannot accept values that start with `-`

In trying to set an RSA key which starts with -----BEGIN RSA PRIVATE KEY-----, the command line helper dotenv set fails with the following:

Error: no such option: [my-secret-value]

That should be enough to recreate. Any thoughts?

Bash exporting results of dotenv get

I've been trying to use dotenv get in a bash script however due to dotenv returning the variable name and quoting the value this is proving to be somewhat annoying.

.env:

FOO="foo bar"

The cleanest solution I have so far which isn't going to work if I ever have a value with a double quote in it:

$ foo=`dotenv get FOO`
$ declare -x "${foo//\"/}"

Is there any guidance on this?

I was thinking this would be easier if I could get get to return just the value.

AttributeError: 'module' object has no attribute 'group'

when I import dotenv the program crashed.

python version 2.7.13


Traceback (most recent call last):
  File "/home/ysw/Code/pyspark/main.py", line 5, in <module>
    from dotenv import load_dotenv, find_dotenv
  File "/home/ysw/.virtualenvs/spark/lib/python2.7/site-packages/dotenv/__init__.py", line 1, in <module>
    from .cli import get_cli_string
  File "/home/ysw/.virtualenvs/spark/lib/python2.7/site-packages/dotenv/cli.py", line 8, in <module>
    @click.group()
AttributeError: 'module' object has no attribute 'group'

These are my pip list:


astroid (1.5.3)
autopep8 (1.3.2)
backports.functools-lru-cache (1.4)
backports.shutil-get-terminal-size (1.0.0)
click (6.7)
configparser (3.5.0)
decorator (4.1.2)
enum34 (1.1.6)
ipython (5.4.1)
ipython-genutils (0.2.0)
isort (4.2.15)
lazy-object-proxy (1.3.1)
mccabe (0.6.1)
pathlib2 (2.3.0)
pexpect (4.2.1)
pickleshare (0.7.4)
pip (9.0.1)
prompt-toolkit (1.0.15)
ptyprocess (0.5.2)
py4j (0.10.4)
pycodestyle (2.3.1)
Pygments (2.2.0)
pylint (1.7.2)
pymongo (3.5.1)
PyMySQL (0.7.11)
pyspark (2.2.0)
python-dotenv (0.7.1)
scandir (1.5)
setuptools (36.2.7)
simplegeneric (0.8.1)
singledispatch (3.4.0.3)
six (1.10.0)
SQLAlchemy (1.1.13)
traitlets (4.3.2)
wcwidth (0.1.7)
wheel (0.29.0)
wrapt (1.10.11)

Multiline value not working as expected, better doc example needed

I have this .env file

CLOUDKARAFKA_CA="-----BEGIN CERTIFICATE-----
MIIDAzCCAeugAwIBAgIJAL7UBqvWBRglMA0GCSqGSIb3DQEBCwUAMBgxFjAUBgNV
someMoreLines
+HPBLZVg3o4jtzOJJNnaGCAcAHsm6PkqBhTUhM113r8MWlsR6eAIhIVtdRAxmjaw
6f7ARs8C8A==
-----END CERTIFICATE-----
"
CLOUDKARAFKA_CERT="-----BEGIN CERTIFICATE-----
MIICpzCCAY8CCQCA4JIEmpl1oTANBgkqhkiG9w0BAQsFADAYMRYwFAYDVQQDDA12
someMoreLines
SSgZPE8qiN/jucTdLSLRQ0igohq4EnAg8QHXReX2oIlSZb7i8wxCqK/T+9WU0+vB
ToJ+bM0OCJ4d22I=
-----END CERTIFICATE-----
"
CLOUDKARAFKA_TOPIC_PREFIX="aj9g740d-"
CLOUDKARAFKA_BROKERS="velomobile-02.srvs.cloudkafka.com:9094,velomobile-01.srvs.cloudkafka.com:9094,velomobile-03.srvs.cloudkafka.com:9094"

When I use this .env file, the CLOUDKARAFKA_CA and CLOUDKARAFKA_CERT key are both "-----BEGIN CERTIFICATE-----"

image

Notice the extra ", Am I doing something wrong, please help

Fix warning by Click library about unicode / Python3

Warning: Click detected the use of the unicode_literals __future__ import.  This is heavily discouraged because it can introduce subtle bugs in your code.  You should instead use explicit u"" literals for your unicode strings.  For more information see http://click.pocoo.org/python3/

too many values to unpack

I am using
python-dotenv (0.6.1)

content of my .env file

cat .env
DOMAIN="example.org"
a="b"

tonychia@Tonys-MacBook-Pro ~ $ dotenv list
Traceback (most recent call last):
  File "/usr/local/bin/dotenv", line 11, in 
    sys.exit(cli.cli())
  File "/Library/Python/2.7/site-packages/click/core.py", line 722, in __call__
    return self.main(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/click/core.py", line 697, in main
    rv = self.invoke(ctx)
  File "/Library/Python/2.7/site-packages/click/core.py", line 1066, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Library/Python/2.7/site-packages/click/core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Library/Python/2.7/site-packages/click/core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/click/decorators.py", line 17, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/Library/Python/2.7/site-packages/dotenv/cli.py", line 29, in list
    for k, v in dotenv_as_dict:
ValueError: too many values to unpack

charmap error on pip install in Windows

pip install -U python-dotenv
Collecting python-dotenv
Using cached python-dotenv-0.6.2.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "C:\Users...\AppData\Local\Temp\pip-build-q6z2d_sj\python-dotenv\setup.py", line 5, in
readme = readme_file.read()
File "c:\users\hanan.shteingart\anaconda3\lib\encodings\cp1255.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9c in position 1067: character maps to

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in C:\Users...\AppData\Local\Temp\pip-build-q6z2d_sj\python-dotenv\

Option for Docker compatibility

I was hoping to use python-dotenv to re-use the env file created for Docker. The Docker syntax, however, conflicts with the python-dotenv syntax (in how it interprets quotes).

Should python-dotenv provide a mode that's compatible with Docker's syntax?

Error when installing with Python 3.6

To reproduce (using a temporary environment set up with conda):

# Create temporary conda environment `tmpenv`
$ conda create --name tmpenv python=3.6
$ source activate tmpenv

# Try to install dotenv
$ pip install dotenv
# Error! See output below.

# Remove temporary conda environment
$ source deactivate tmpenv
$ conda remove --name tmpenv --all

The installation works fine with Python 3.5.

Here is the output of the pip install dotenv command.

Collecting dotenv
  Using cached dotenv-0.0.5.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/sandbox.py", line 156, in save_modules
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/sandbox.py", line 196, in setup_context
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/easy_install-no05k7m3/distribute-0.7.3/setuptools/__init__.py", line 2, in <module>
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/easy_install-no05k7m3/distribute-0.7.3/setuptools/extension.py", line 5, in <module>
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/easy_install-no05k7m3/distribute-0.7.3/setuptools/dist.py", line 7, in <module>
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/easy_install-no05k7m3/distribute-0.7.3/setuptools/command/__init__.py", line 8, in <module>
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/easy_install-no05k7m3/distribute-0.7.3/setuptools/command/install_scripts.py", line 3, in <module>
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/easy_install-no05k7m3/distribute-0.7.3/pkg_resources.py", line 1518, in <module>
    AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader'
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/pip-build-il9z1kn9/dotenv/setup.py", line 23, in <module>
        scripts=['scripts/dotenv']
      File "~/miniconda3/envs/tmpenv/lib/python3.6/distutils/core.py", line 108, in setup
        _setup_distribution = dist = klass(attrs)
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/dist.py", line 315, in __init__
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/dist.py", line 361, in fetch_build_eggs
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/pkg_resources/__init__.py", line 851, in resolve
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/pkg_resources/__init__.py", line 1123, in best_match
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/pkg_resources/__init__.py", line 1135, in obtain
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/dist.py", line 428, in fetch_build_egg
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/command/easy_install.py", line 664, in easy_install
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/command/easy_install.py", line 694, in install_item
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/command/easy_install.py", line 875, in install_eggs
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/command/easy_install.py", line 1114, in build_and_install
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/command/easy_install.py", line 1100, in run_setup
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/sandbox.py", line 235, in run_setup
      File "~/miniconda3/envs/tmpenv/lib/python3.6/contextlib.py", line 82, in __enter__
        return next(self.gen)
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/sandbox.py", line 197, in setup_context
      File "~/miniconda3/envs/tmpenv/lib/python3.6/contextlib.py", line 100, in __exit__
        self.gen.throw(type, value, traceback)
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/sandbox.py", line 168, in save_modules
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/sandbox.py", line 143, in resume
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/pkg_resources/_vendor/six.py", line 685, in reraise
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/sandbox.py", line 156, in save_modules
      File "~/miniconda3/envs/tmpenv/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg/setuptools/sandbox.py", line 196, in setup_context
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/easy_install-no05k7m3/distribute-0.7.3/setuptools/__init__.py", line 2, in <module>
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/easy_install-no05k7m3/distribute-0.7.3/setuptools/extension.py", line 5, in <module>
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/easy_install-no05k7m3/distribute-0.7.3/setuptools/dist.py", line 7, in <module>
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/easy_install-no05k7m3/distribute-0.7.3/setuptools/command/__init__.py", line 8, in <module>
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/easy_install-no05k7m3/distribute-0.7.3/setuptools/command/install_scripts.py", line 3, in <module>
      File "/private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/easy_install-no05k7m3/distribute-0.7.3/pkg_resources.py", line 1518, in <module>
    AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader'
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/b1/npl0095x3s96s_vfsb5_60d00000gq/T/pip-build-il9z1kn9/dotenv/

Error when loading dotenv in Python 3.2

I'm using dotenv as part of my tests and I'm getting a problem when trying to load it in Python 3.2

Travis error

Error:

../../../virtualenv/python3.2.5/lib/python3.2/site-packages/_pytest/python.py:591: in _importtestmodule
    mod = self.fspath.pyimport(ensuresyspath=importmode)
../../../virtualenv/python3.2.5/lib/python3.2/site-packages/py/_path/local.py:650: in pyimport
    __import__(modname)
../../../virtualenv/python3.2.5/lib/python3.2/site-packages/_pytest/assertion/rewrite.py:171: in load_module
    py.builtin.exec_(co, mod.__dict__)
test/test_examples.py:10: in <module>
    from dotenv import load_dotenv
../../../virtualenv/python3.2.5/lib/python3.2/site-packages/dotenv.py:10: in <module>
    import click
../../../virtualenv/python3.2.5/lib/python3.2/site-packages/click/__init__.py:18: in <module>
    from .core import Context, BaseCommand, Command, MultiCommand, Group, \
../../../virtualenv/python3.2.5/lib/python3.2/site-packages/click/core.py:8: in <module>
    from .types import convert_type, IntRange, BOOL
../../../virtualenv/python3.2.5/lib/python3.2/site-packages/click/types.py:7: in <module>
    from .exceptions import BadParameter
../../../virtualenv/python3.2.5/lib/python3.2/site-packages/click/exceptions.py:2: in <module>
    from .utils import echo
E     File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/click/utils.py", line 279
E       message = message or u''
E                              ^
E   SyntaxError: invalid syntax

Allow variables to be prefixed with "export"

Hi there. In Rust there's also a dotenv library which is very similar but has a nice additional feature:

You can optionally prefix each line with the word export, which will conveniently allow you to source the whole file on your shell.

So a .env file essentially has extended syntax which makes the following valid:

export MY_API_KEY="blah"

This comes in handy because during local development because some command line developer tools need access to the same environment variables that your application does (e.g. if you want to use curl to test an API endpoint that your application uses).

dotenv keeps '\r' at end of variables in django

Is it possible to strip my variables when I from dotenv import load_dotenv it keeps the trailing '\r' on my variables which is breaking my build and I have to manually update my variables or call os.environ['env_variable'].strip().

How can I avoid this?

Windows: Unicode Character is not escaped

I've noted when using a windows machine, a Unicode character is added to every value.

'OS': 'Windows_NT',
'EXAMPLE_KEY': u'EXAMPLE_VALUE'

This is using the example listed in the README.

Variable not found ("None" returned) on a Mac

Hi, we are using dotenv for a project and are getting strange behavior.

While the environment variable is working just fine on a Windows machine, it is not able to read at all on a Mac. It returns "None" even though the variable is clearly there. There seem to be no other issues.

In X.py file:

from dotenv import load_dotenv
load_dotenv()
import os
HOME_PATH = os.getenv("SQUABBLE_HOME_PATH")

In .env file:

SQUABBLE_HOME_PATH = '/path/to/squabble_runner/'

While running:

Traceback (most recent call last):
  File "XXXX/X.py", line 27, in controversy_score
    input_file_path = HOME_PATH + 'lib/squabble_input.txt'
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

This is on Sierra, Python 3.6.2.

As mentioned above, the same code runs just fine on a PC.
Any help would be appreciated!

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1065: ordinal not in range(128)

On setup:

P3.4

Collecting python-dotenv (from -r requirements.txt (line 4))
  Downloading python-dotenv-0.6.2.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-v231dm4e/python-dotenv/setup.py", line 5, in <module>
        readme = readme_file.read()
      File "/usr/lib/python3.4/encodings/ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1065: ordinal not in range(128)
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-v231dm4e/python-dotenv/

P3.5

Collecting python-dotenv (from -r requirements.txt (line 4))
  Downloading python-dotenv-0.6.2.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-s94tagti/python-dotenv/setup.py", line 5, in <module>
        readme = readme_file.read()
      File "/usr/lib/python3.5/encodings/ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1065: ordinal not in range(128)
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-s94tagti/python-dotenv/

Fabric example is not working

fab config:set,hello=world
Executing task 'config'
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/fabric/main.py", line 743, in main
    *args, **kwargs
  File "/Library/Python/2.7/site-packages/fabric/tasks.py", line 387, in execute
    multiprocessing
  File "/Library/Python/2.7/site-packages/fabric/tasks.py", line 277, in _execute
    return task.run(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/fabric/tasks.py", line 174, in run
    return self.wrapped(*args, **kwargs)
TypeError: config() got an unexpected keyword argument 'hello'

fabric parses the hello=world and passes it to the config task as a keyword argument. I had to use:

@task
def config(action=None, **kwargs):
    """Manage project configuration via .env

    e.g: fab config:set,<key>=<value>
         fab config:get,<key>
         fab config:unset,<key>
         fab config:list
    """
    if len(kwargs):
        k, v = list(kwargs.items())[0]
        if v:
            key_value = "{}={}".format(k, v)
        else:
            key_value = k
    else:
        key_value = None
    command = dotenv.get_cli_string(env.dotenv_path, action, key_value)
    with environment():
        run(command)

But then fab config:unset,hello does not work anymore...

Parser should ignore whitespace and set types

The parser should strip leading and trailing whitespace on KEY and "Value" and also set types for booleans r'(?i)(true|false) and integers r'[0-9]*'

Happy to submit a PR for this, mostly just wondering if you agree that these things should happen

Support for multi line environment variables

Similar to bkeepers/dotenv#21

I have keys that include newlines, but python-dotenv can't read those. Similar to other solutions, a good solution might be to delimit newlines within quotes. Alternatively, a solution could involve preserving the newline character--currently read in by Python as '\n'.

Is there any interest in such a PR?

Initial Update

Hi 👊

This is my first visit to this fine repo, but it seems you have been working hard to keep all dependencies updated so far.

Once you have closed this issue, I'll create separate pull requests for every update as soon as I find one.

That's it for now!

Happy merging! 🤖

python3 only?

In Ubuntu, I get RuntimeError: uvloop requires Python 3.5 or greater

But

python3 src/chess_zero/run.py self
Traceback (most recent call last):
File "src/chess_zero/run.py", line 19, in
from chess_zero import manager
File "src/chess_zero/manager.py", line 38
logger.info(f"config type: {config_type}")
SyntaxError: invalid syntax

Is some typo lurking in the code? ^

find_dotenv doesn't work as expected

What I did

from dotenv import find_dotenv, load_dotenv
load_dotenv(find_dotenv())

What I expected

The .env file to be loaded properly

What I got

The .env file was not found

Additional information

I print-debugged the code and found the following path when it walks up the directory tree

/usr/local/lib/python3.5/site-packages/dotenv
/usr/local/lib/python3.5/site-packages
/usr/local/lib/python3.5
/usr/local/lib
/usr/local
/usr
/

This might be from the usage of __file__ in that module.

Is this the intended behavior of find_dotenv?

django-configurations support

Hei,

Seems like the support in django-configurations for dotenv seems to be in the master.
Update the README?

Thanks for a great lib!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.