I want to write in the .env using python code. This is what I tried but it's not working:-
os.environ['username'] = 'John'
os.environ['email'] = 'abc@gmail.com'
I want to write in the .env using python code. This is what I tried but it's not working:-
os.environ['username'] = 'John'
os.environ['email'] = 'abc@gmail.com'
os.environ is a Python dictionary containing the environment. In order to change the environment variables in your currently running process, and any children process spawned with fork, you should use os.putenv as follows:
import os
os.putenv("username", "John")
os.putenv("email", "abc@gmail.com")
Do notice, this changes are not permanent, they just affect the process being currently executed.
If you want the changes to be permanent, you can write them to a .env file, and read and reset them on startup:
with open(".env", "r") as f:
for line in f.readlines():
try:
key, value = line.split('=')
os.putenv(key, value)
except ValueError:
# syntax error
pass
To generate the file you should:
with open(".env", "w") as f:
f.write("username=John")
f.write("email=abc@gmail.com")
If you want to permanently change this environment variables on the whole OS scope, you need an OS specific solution, since each operating system has its way of changing environment variables.
This method will set the environment variable globally, which will affect all applications run and not just yours, so be extremely careful on what are you writing to.
Unix-like systems like Linux and macOS let you set up these variables in .profile, so you may do something like this (Python 3.5+):
from pathlib import Path
with open(str(Path.home()) + "/.profile", "a") as f:
f.write("export USERNAME=John\nexport EMAIL abc@gmail.com\n")
On Windows on the other hand you should call setx:
import subprocess
subprocess.call(["setx", "USERNAME", "John"])
subprocess.call(["setx", "EMAIL", "abc@gmail.com"])