0
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
    "while the python process is running but as soon as the python process is terminated, the environment variable changes do not persist." That's *always how environment variables work*. The question you linked has an answer that explains this in detail. It really isn't clear what you are asking. – juanpa.arrivillaga May 18 '23 at 17:23
  • 2
    "but i was hoping there may be new solutions to this problem" The solution is "don't do this". This *shouldn't be a problem*. Why don't you explain *what you are actually trying to accomplish*? Otherwise, this should get closed as a duplicate of: https://stackoverflow.com/questions/716011/why-cant-environmental-variables-set-in-python-persist – juanpa.arrivillaga May 18 '23 at 17:28
  • 1
    How persistent do you need this to be? If I `export my_variable=hello world` it is only "persistent" for programs run from that shell. If you want something truly persistent across new shells being executed and across reboots, you need to update something like .bashrc. From a different perspective, if you only need this for other python scripts you write and can control how they work, you could store the environment variables in some well known format in a well known file and have your program read them. – tdelaney May 18 '23 at 18:01

1 Answers1

0

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