1

I have this simple environment set script in Python:

import os
os.environ['API_USER'] = 'SuperUser'
os.environ['API_PASSWORD'] = 'SuperPass'

USER = os.environ.get('API_USER')
PASSWORD = os.environ.get('API_PASSWORD')

print(USER)
print(PASSWORD)

When I run it I get this:

SuperUser
SuperPass

So far OK, but when I comment out two lines where I set user and pass and run it again, I get this:

None
None

Why those two environment variable are removed and are not saved? I was wondering, that once I set some environment variable, I can use it again later without setting it again (until I delete them), right? What is wrong? Thank you!

wotesi
  • 319
  • 1
  • 3
  • 15
  • 3
    If I remember it correctly, Environment variables set inside a process are available only inside the same process. If you want to make these environment variables across process, I think you need to use SETX, see this post https://stackoverflow.com/questions/488366/how-do-i-make-environment-variable-changes-stick-in-python – Hussain Bohra Feb 26 '21 at 17:54

1 Answers1

2

You are only setting the environment variable for that specific running Python process. Once the process exits, the variable ceases to exist. It appears you cannot set a persistent environment variable from Python, as is described here:

Why can't environmental variables set in python persist?

It looks like you'll need to shell execute whatever variable you want to persist, as is described in the second answer to the above questions, like so:

import pipes
import random
r = random.randint(1,100)
print("export BLAHBLAH=%s" % (pipes.quote(str(r))))

Edit:

As per @SuperStormer's comment below--they are correct--this solution is Unix/Mac specifc. If you need to accomplish the same thing on Windows you would utilize setx like so (this would set the variable for only current user, you need to add a /m switch on the end to set for the local machine):

import pipes
import random
r = random.randint(1,100)
print("setx BLAHBLAH %s" % (pipes.quote(str(r))))
cjones26
  • 3,459
  • 1
  • 34
  • 51
  • 2
    pipes -> shlex(that's where pipes imports quote from anyways). Note that this solution is unix-specific, windows uses setx instead. – SuperStormer Feb 26 '21 at 17:57