执行export命令后Python无法获取环境变量?该如何解决?
os.environ['AUTOTEST'] after setting the environment variable Let's break down this issue and fix it step by step—this is a common pitfall with shell environment variables and child processes like Python.
First, let's recap your exact steps and the error you hit:
Your Shell & Python Session
λ: export AUTOTEST=/home/anton/eltx/scripts/gitlab/ ~ λ: python
Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ['AUTOTEST'] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/UserDict.py", line 40, in __getitem__ raise KeyError(key) KeyError: 'AUTOTEST'
Why This Happens
When you use export to set an environment variable, it only exists in your current shell session and any child processes started from that session. If Python isn't inheriting this variable, it's almost always one of two reasons:
- You started Python in a different shell window (new shells don't inherit variables from previous sessions)
- There's a shell configuration quirk that's clearing or overriding the variable before Python starts
Fixes to Try
1. Pass the Variable Directly When Starting Python
This is the most reliable way to ensure the variable reaches the Python process:
AUTOTEST=/home/anton/eltx/scripts/gitlab/ python
Once you enter the Python shell with this command, os.environ['AUTOTEST'] will return the correct path immediately.
2. Verify the Variable Exists in Your Shell First
Before launching Python, confirm the variable is set in your current shell:
echo $AUTOTEST
If this outputs the correct path, then launching Python in the same window should work. If it doesn't, re-run the export command and double-check you're in the same shell session.
3. Persist the Variable for Future Sessions
If you want AUTOTEST to be available every time you open a shell, add the export line to your shell's config file:
- For Bash: Edit
~/.bashrcor~/.bash_profileand addexport AUTOTEST=/home/anton/eltx/scripts/gitlab/ - For Zsh: Edit
~/.zshrcwith the same line
After adding it, run source ~/.bashrc (or your config file) to apply the change immediately. From then on, any Python process started from your shell will see the variable.
4. Debug by Checking All Environment Variables
If none of the above work, list all environment variables in Python to confirm if AUTOTEST is missing:
import os # Print all environment variable keys for key in os.environ.keys(): print(key)
If AUTOTEST isn't in the list, go back to verifying your shell's variable setup—there's a disconnect between your shell and the Python process.
内容的提问来源于stack exchange,提问作者Anton Kharchenko

