5

I have a pretty interesting problem regarding environment variables, and googling around didn't show me any meaningful results:

$ echo $BUCKET && python -c "import os; print os.environ['BUCKET']" mule-uploader-demo Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__ raise KeyError(key) KeyError: 'BUCKET' 

So I have an environment variable that is available in bash but not inside python. How can this happen and how do I fix it? Here are some additional details:

  • The environment variable is set through a source envvars.sh command
  • The envvars.sh file contains only lines that look like this: KEY=value
  • I've reproduced this in both bash and zsh
  • If I do an export BUCKET=$BUCKET, it works
2
  • can you do env | grep BUCKET? if it's not exported it won't be available to child processes. Commented Jan 10, 2015 at 17:35
  • nope, it's not in there. But why? I can echo $BUCKET Commented Jan 10, 2015 at 17:37

1 Answer 1

5

This has to do with the variable scope in bash. export makes your variable available to subprocesses, see for example:

→ export BUCKET=foo → env | grep BUCKET 80:BUCKET=foo → PAIL=bar → env | grep PAIL # no output → python -c "import os; print os.environ['BUCKET']" foo → python -c "import os; print os.environ['PAIL']" Traceback (most recent call last): File "<string>", line 1, in <module> File "...", line 23, in __getitem__ raise KeyError(key) KeyError: 'PAIL' → CAN=baz python -c "import os; print os.environ['CAN']" baz 

so in a child process PAIL is a fail.

1
  • Yeah, I thought that using source [filename] would export the variables automatically, but apparently this is not the case. Thanks! Commented Jan 10, 2015 at 18:00

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.