[英]How to set environment variables with python?
I wish to read an .env
file with python and expose the environment variables so they can be accessed by other scripts in the same environment.我希望使用 python 读取
.env
文件并公开环境变量,以便同一环境中的其他脚本可以访问它们。 I have this script:我有这个脚本:
from dotenv import load_dotenv
import os
load_dotenv("common.env")
print(os.environ["CONFIG_FOLDER_NAME"])
When I run this script it prints the correct value.当我运行此脚本时,它会打印正确的值。
However when I try to read the variables from a different file they don't seem to exist.但是,当我尝试从不同的文件中读取变量时,它们似乎不存在。 Even if I do
echo $CONFIG_FOLDER_NAME
it return empty.即使我
echo $CONFIG_FOLDER_NAME
它也返回空。
Ok so based on the comment above, to help future users who might not be aware of this, you cannot set environment variables from Python .好的,根据上面的评论,为了帮助可能不知道这一点的未来用户,您不能从 Python 设置环境变量。
You can make python aware of some variables but they want be actually accessible in the environment.您可以让 python 了解一些变量,但它们希望在环境中实际可访问。
I found three ways to actually set the variables by:我找到了三种实际设置变量的方法:
launch.json
for setting the variables either with env
or envFile
launch.json
使用env
或envFile
设置变量Docker
file or docker-compose.yml
if you are containerizing your appDocker
文件或docker-compose.yml
定义它们Note: If there are other options to address this please comment and I ll add them.注意:如果还有其他选项可以解决此问题,请发表评论,我会添加它们。 I want this to be a helpfull post for new developers like myself.
我希望这篇文章对像我这样的新开发人员有帮助。 Shaming and non-helpful comments never helped anyone or improved anything.
羞辱和无益的评论从来没有帮助过任何人或改善过任何事情。 This is, or should be, a learning and knowledge exchange platform and it should be open to all programming questions
这是或应该是一个学习和知识交流平台,它应该对所有编程问题开放
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.