使用 Python 和 dotenv 更改保存在 .env 文件中的环境变量
Change Environment Variables Saved In .env File With Python and dotenv
我正在尝试使用 python 更新 .env 环境变量。使用 os.environ
我可以查看和更改本地环境变量,但我想更改 .env 文件。使用 python-dotenv
我可以将 .env 条目加载到本地环境变量中
.env 文件
key=value
test.py
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
print(os.environ['key']) # outputs 'value'
os.environ['key'] = "newvalue"
print(os.environ['key']) # outputs 'newvalue'
.env 文件
key=value
.env 文件未更改!仅更改本地环境变量。我找不到任何关于如何更新 .env 文件的文档。有人知道解决方案吗?
import dotenv
dotenv_file = dotenv.find_dotenv()
dotenv.load_dotenv(dotenv_file)
print(os.environ["key"]) # outputs "value"
os.environ["key"] = "newvalue"
print(os.environ['key']) # outputs 'newvalue'
# Write changes to .env file.
dotenv.set_key(dotenv_file, "key", os.environ["key"])
我正在尝试使用 python 更新 .env 环境变量。使用 os.environ
我可以查看和更改本地环境变量,但我想更改 .env 文件。使用 python-dotenv
我可以将 .env 条目加载到本地环境变量中
.env 文件
key=value
test.py
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
print(os.environ['key']) # outputs 'value'
os.environ['key'] = "newvalue"
print(os.environ['key']) # outputs 'newvalue'
.env 文件
key=value
.env 文件未更改!仅更改本地环境变量。我找不到任何关于如何更新 .env 文件的文档。有人知道解决方案吗?
import dotenv
dotenv_file = dotenv.find_dotenv()
dotenv.load_dotenv(dotenv_file)
print(os.environ["key"]) # outputs "value"
os.environ["key"] = "newvalue"
print(os.environ['key']) # outputs 'newvalue'
# Write changes to .env file.
dotenv.set_key(dotenv_file, "key", os.environ["key"])