使用 Python 和 dotenv 更改保存在 .env 文件中的环境变量

Dyl*_*ley 2 python environment-variables dotenv

我正在尝试用 python 更新 .env 环境变量。随着os.environ我能够查看和更改本地环境变量,但我想改变.ENV文件。使用python-dotenv我可以将 .env 条目加载到本地环境变量中

.env 文件

key=value
Run Code Online (Sandbox Code Playgroud)

测试文件

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'
Run Code Online (Sandbox Code Playgroud)

.env 文件

key=value
Run Code Online (Sandbox Code Playgroud)

.env 文件没有改变!仅更改了本地 env 变量。我找不到有关如何更新 .env 文件的任何文档。有谁知道解决方案?

Jak*_*kub 11

使用dotenv.set_key.

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"])
Run Code Online (Sandbox Code Playgroud)