简体   繁体   English

VSCode 上的 Python 脚本中未访问环境变量

[英]Environment variables not being accessed in Python script on VSCode

I am creating a simple app that connects to an API and stores specific data into a list.我正在创建一个连接到 API 并将特定数据存储到列表中的简单应用程序。 In order to connect to the API, I must do BasicAuth with an email and password.为了连接到 API,我必须使用 email 和密码进行 BasicAuth。 Whenever I hardcode my email and password into the Python script, it works perfectly, however whenever I store these values in a .env file and do os.getenv('EMAIL') , I am getting a 401 error.每当我将 email 和密码硬编码到 Python 脚本中时,它都能正常工作,但是每当我将这些值存储在.env文件中并执行os.getenv('EMAIL')时,我都会收到 401 错误。 I proceeded to print out the value of EMAIL and PASSWORD when EMAIL = os.getenv('EMAIL') and PASSWORD = os.getenv('PASSWORD') but it is printing None in the console.EMAIL = os.getenv('EMAIL')PASSWORD = os.getenv('PASSWORD')但它在控制台中打印 None 时,我继续打印出 EMAIL 和 PASSWORD 的值。 Here is my code in the Python script:这是我在 Python 脚本中的代码:

    load_dotenv()
    EMAIL = os.getenv('EMAIL')
    PASSWORD = os.getenv('PASSWORD')

Here is what my.env file looks like:这是 my.env 文件的样子:

    EMAIL = importantemail@mydomain.com  
    PASSWORD = secret_password

The two files are in the same folder but I am thinking that I need to do something like pointing my working directory to the folder that has the script and the.env file.这两个文件在同一个文件夹中,但我认为我需要做一些事情,比如将我的工作目录指向包含脚本和 .env 文件的文件夹。 This is my first full-fledged project so I believe that I am missing something obvious.这是我第一个成熟的项目,所以我相信我遗漏了一些明显的东西。

os.getenv() is for system environment variables like HOME , PATH , etc. This function does not read any data from your .env file. os.getenv()用于系统环境变量,如HOMEPATH等。此 function 不会从您的.env文件中读取任何数据。

You can use this parser , or parse file by your own with os package.您可以使用此解析器,也可以使用os package 自行解析文件。

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

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