python用户环境变量找不到_Python为什么看不到环境变量?

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 "", line 1, in

File "/root/.virtualenvs/prescribing/lib/python2.7/UserDict.py", line 23, in __getitem__

raise KeyError(key)

KeyError: 'SECRET_KEY'

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

SECRET_KEY=xxx-xxx-xxx

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

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

Demo:

$ 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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值