2

I have the following environment variables in my .env file:

DT="2019-01-01"
X=${DT//-/}

The variable X has been set using Bash's parameter replacement, using the ${parameter//pattern/string} format to replace all occurrences (Documentation here).

Now, to read the environment variables into Python, I have created a Python class Config in a file config.py:

from dotenv import find_dotenv, load_dotenv
import os

class Config:
    def __init__(self):
        load_dotenv(find_dotenv())

        self.X = os.environ.get('X')

In a python shell, I run:

In [1]: from config import Config

In [2]: c = Config()

In [3]: c.X
Out[3]: ''

Here c.X is an empty string '', where as I want it to be '20190101'.

How do I load the correct value of the environment variable into a python variable?

Edit: When I type echo $X in a bash script, it prints the correct value. For example, a bash script sample.sh:

#!/bin/bash
source .env

echo $X

When run, I get:

$ sh sample.sh
20190101
5
  • 1
    I don't see you referencing DT anywhere. Commented Mar 27, 2019 at 15:49
  • also try $ env in your bash first to make sure X is set to what you want. Commented Mar 27, 2019 at 15:50
  • Have edited the question for clarifications @hiroprotagonist Commented Mar 27, 2019 at 15:55
  • 2
    how do you start python then? you may have to export X in bash... Commented Mar 27, 2019 at 16:05
  • @hiroprotagonist, I added the export, it works the way I need it to now, thanks! :D Commented Mar 27, 2019 at 16:23

2 Answers 2

2

I added an export in my .env file in this way:

DT="2019-01-01"
export X=${DT//-/}

This allowed me to get the correct value of c.X in Python.

Sign up to request clarification or add additional context in comments.

Comments

0

Dotenv does not use Bash; it parses the file internally. See the dotenv GitHub page.

Directly use DT instead:

self.X = os.environ.get('DT').replace('-', '')

1 Comment

I need to use the variable X without hyphens as a part of another variable name later on in my .env file as well. It would be better if I could resolve this in the .env file itself rather than in Python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.