Home > database >  How to access 'missing' Environmental variables?
How to access 'missing' Environmental variables?

Time:11-07

I am adding an environmental variable in bashrc, but am unable to see the variables using os.environ.get in a Python file.

I am using Raspbian on a Raspberry Pi 4.

I am setting an environmental variable in “bashrc” as follows:

export DB_USER='[email protected]'

When calling the following on Terminal:

$ env

…I find DB_USER in a the list of 24 items.

However, when I use the following in a Python file (this file is called by a bash script):

import os
...
try:
    with open("tempFile.txt", "a") as f:
        f.write(str(os.environ))
        f.close()
except FileNotFoundError:
    print("FileNotFoundError")
except IOError:
    print("IOError")

then ‘DB_USER’ is not in the list of 11 entries in "tempFile.txt".

How can I access the list of 24 items so that I can use ‘DB_USER’ entry?

Thanks

CodePudding user response:

Since this is a service (so, not your user, as per Chepner's comment) calling something this looks like you want to make the environment variable available system-wide.

/etc/environment may fit your needs. You would just add

[email protected]

to it. (no, don't use export)

See also https://superuser.com/questions/664169/what-is-the-difference-between-etc-environment-and-etc-profile and https://raspberrypi.stackexchange.com/questions/37771/setting-system-wide-path-not-working-in-etc-environment (which talks about using /etc/profile.d instead, but similar concept - that's probably the approach I'd take, after testing a basic /etc/environment based fix)

CodePudding user response:

Try something like this:

import os, subprocess

# try to simulate being the user so you can import/capture the env as that user
cmd = 'env -i sh -c ". /home/user/.bashrc && env"'

try:
    with open("tempFile.txt", "a") as f:
        for line in subprocess.getoutput(cmd).split("\n"):
        f.write(str(line))
        f.close()
except FileNotFoundError:
    print("FileNotFoundError")
except IOError:
    print("IOError")

  • Related