为什么 Python 看不到环境变量?

2022-01-16 00:00:00 python environment-variables bash

问题描述

我正在使用 Python 2 开发 Debian Jessie.为什么 Python 的 environ 看不到 bash 中可见的环境变量?

I'm working on Debian Jessie with Python 2. Why can't Python's environ see environment variables that are visible in bash?

# echo $SECRET_KEY
xxx-xxx-xxxx
# python
>>> from os import environ
>>> environ["SECRET_KEY"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/root/.virtualenvs/prescribing/lib/python2.7/UserDict.py", line 23, in __getitem__
    raise KeyError(key)
KeyError: 'SECRET_KEY'

我使用 /etc/environment 设置这些环境变量 - 不确定这是否相关:

I set these environment variables using /etc/environment - not sure if that's relevant:

SECRET_KEY=xxx-xxx-xxx

我必须运行 source/etc/environment 才能让 bash 看到它们,我认为这很奇怪.

I had to run source /etc/environment to get bash to see them, which I thought was strange.

更新: printenv SECRET_KEY 什么也没产生,所以我猜 SECRET_KEY 是一个shell而不是一个环境变量.

UPDATE: printenv SECRET_KEY produces nothing, so I guess SECRET_KEY is a shell not an environment variable.


解决方案

你需要导出环境变量让子进程看到:

You need to export environment variables for child processes to see them:

export SECRET_KEY

演示:

$ SECRET_KEY='foobar'
$ bin/python -c "import os; print os.environ.get('SECRET_KEY', 'Nonesuch')"
Nonesuch
$ export SECRET_KEY
$ bin/python -c "import os; print os.environ.get('SECRET_KEY', 'Nonesuch')"
foobar

您可以一步结合设置和导出:

You can combine the setting and exporting in one step:

export SECRET_KEY=xxx-xxx-xxxx

请注意,/etc/environment 中的新变量不会自动显示在您现有的 shell 中,除非您有 新登录.对于 GUI 桌面,您必须注销并再次登录,对于 SSH 会话,您必须创建新的 SSH 登录.只有这样,您才能获得一个新的进程树,其中包含更改.使用 source/etc/environment 仅设置本地"变量(文件不是脚本).请参阅 如何在不重启的情况下重新加载/etc/environment?用户.

Note that new variables in /etc/environment do not show up in your existing shells automatically, not until you have a new login. For a GUI desktop, you'll have to log out and log in again, for SSH sessions you'll have to create a new SSH login. Only then will you get a new tree of processes with the changes present. Using source /etc/environment only sets 'local' variables (the file is not a script). See How to reload /etc/environment without rebooting? over on Super User.

相关文章