os.environ.get returns variable as 'None', even though it can be echoed in terminal. (Python) (Mac OS Catalina)

Viewed 1447

I am trying to call a variable which has been exported in the .bash_profile file. This is how it has been written.

export TEST='test'

After saving this change in the .bash_profile file, I type this into terminal:

source ~/.bash_profile

Upon typing env into terminal, TEST=test is shown. Furthermore, upon typing echo $TEST, terminal returns test.

The problem I have is that when I try to call this variable into a python script using Pycharm, the script returns None.

The code is:

import os

print(os.environ.get('TEST'))

How can I get the script to output test?

It is also worth noting that this is all being done in a Conda virtual environment.

What have I done wrong?

1 Answers

I had the same problem. Just figured it out:

In Catalina, Mac now uses zsh instead of bash shell, so variables are stored in a .zshenv file in your home directory instead of .bash_profile:

  1. Go to your home directory:

    cd $HOME

  2. Access your enviroment variable file:

    nano .zshenv

  3. Create variables

    TEST='test' (If you are only going to use it directly from Terminal)

    export TEST2='test2' (If you want to access it with os.environ.get)

    Save and quit terminal. Open another terminal window and check you can access the variable using:

echo $TEST
echo $TEST2
  1. Access the variable with python
import os
username = os.environ.get('TEST2')
print(username)
Related