简体   繁体   English

无法使用 os.environ 声明环境变量

[英]Unable to declare environment variable using os.environ

When I tried setting environment variable value:当我尝试设置环境变量值时:

import os
os.environ['DB_PASSWORD'] = 'Password123'

on PyCharm CE 2020.2, it does not even set the environment variable values for the duration of the Python process or child processes.在 PyCharm CE 2020.2 上,它甚至不会在 Python 进程或子进程的持续时间内设置环境变量值。 It gives me the error:它给了我错误:

DB_PASSWORD
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'DB_PASSWORD' is not defined

Why is it so?为什么会这样? What can be done to get this working without having to manually add the values?无需手动添加值,可以做些什么来使其正常工作?

Here's the screenshot to the error: https://the-inevitable-one.tumblr.com/image/627482222106165248这是错误的屏幕截图: https : //the-inevitable-one.tumblr.com/image/6274822222106165248

os.environ['DB_PASSWORD'] = 'Password123'

This line will export your DB_PASSWORD in environment.DB_PASSWORD在环境中导出您的DB_PASSWORD Environment variables are not Python variables.环境变量不是 Python 变量。

In pycharm, you have opened python interpreter which parses only python code.在 pycharm 中,您打开了仅解析 python 代码的 python 解释器。 It will look for DB_PASSWORD as python variable, not the system environment variable.它将查找DB_PASSWORD作为 python 变量,而不是系统环境变量。

Try putting DB_PASSWORD into your command prompt (cmd or shell) , or in python you can list env variables using尝试将DB_PASSWORD放入您的命令提示符(cmd or shell) ,或者在 python 中,您可以使用列出 env 变量

print(os.environ)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM