How do I persist environment variable changes in python?

530 Views Asked by At
import os
os.environ['my_variable'] = 'hello world'

you are able to edit the environment variable while the python process is running but as soon as the python process is terminated, the environment variable changes do not persist. most work-arounds i have found require an extra step with setting a bash command, alias, or updating .bashrc or .profile but is there a way to do this inside of the python process itself?

there are duplicates of this question of course: Why can't environmental variables set in python persist? but i was hoping there may be new solutions to this problem. thank you

$printenv

import os
os.environ['my_variable'] = 'hello world'

running $printenv command again does not show any changes to env variables

1

There are 1 best solutions below

0
Wilson Wong On

i found something that works

import subprocess
import os
os.environ['username'] = 'user123'
subprocess.run(['/bin/bash', 'source'], shell=True)

apologies for not clarifying the context, i needed this to set environment variables for usernames, passwords, and tokens. hope this helps anyone who runs into the same problem