Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write in .env file from python code

Tags:

python

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'] = '[email protected]'
like image 403
RAVI MISHRA Avatar asked May 12 '26 20:05

RAVI MISHRA


2 Answers

I would like to answer the OP question and speak to the comment by @salius. You can manage your .env files with the package python-dotenv in a principled way. It handles validating the key/value pairs and saving them to a file.

Minimal working example:

$ python3 -m pip install python-dotenv

from dotenv import set_key
from pathlib import Path


env_file_path = Path("/path/to/new/.env")
# Create the file if it does not exist.
env_file_path.touch(mode=0o600, exist_ok=False)
# Save some values to the file.
set_key(dotenv_path=env_file_path, key_to_set="USERNAME", value_to_set="John")
set_key(dotenv_path=env_file_path, key_to_set="EMAIL", value_to_set="[email protected]")

Here is the resulting .env file:

$ cat /path/to/new/.env

USERNAME='John'
EMAIL='[email protected]'
like image 51
Link Swanson Avatar answered May 17 '26 16:05

Link Swanson


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", "[email protected]")

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 protected]")

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 [email protected]\n")

On Windows on the other hand you should call setx:

import subprocess
subprocess.call(["setx", "USERNAME", "John"])
subprocess.call(["setx", "EMAIL", "[email protected]"])
like image 41
Marc Sances Avatar answered May 17 '26 15:05

Marc Sances