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

编程入门 行业动态 更新时间:2024-10-26 02:28:13
本文介绍了Python为什么看不到环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用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.

推荐答案

您需要 export 环境变量以使子进程能够看到它们:

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中的新变量不会自动显示在现有外壳程序中,除非您具有新登录名.对于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.

更多推荐

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

本文发布于:2023-10-16 05:20:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1496619.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:环境变量   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!