How do you access environment variable values without os?

Viewed 640

Using os code is generally accepted as bad practice from a security perspective, as it could potentially provide a bad actor with phenomenal cosmic powers. Nonetheless, most sources appear to recommend using the following to get env variables.

import os
print(os.environ['FOO'])

This approach is also suggested here on SO, such as in "How to access environment variable values?" I know that one can use dotenv to pick up a .env file and to create new env variables, but I have not been able to find anything for existing env variables.

This leads me to the following questions.

  • Is Python's os secure enough to render my concerns unnecessary?
  • Is from os import environ any better than going for the entire import os?
  • Is there a method that is more secure and avoids os entirely?

Thanks muchley!

1 Answers

I was saying that, in general, it is advised to avoid using operating system code for security reasons.

That is not true. Even if by "os code" you mean only Python's os module and not system calls (see the output of man 2 on a UNIX system). You should stop reading (or watching) whatever gave you that impression.

There are a handful of functions which can pose a security risk if used incorrectly. The most notorious being os.popen() when passed a single string as the command to run. When used in that manner the string is interpreted by a subshell and is subject to "word expansion" and "word splitting". Which, in a POSIX shell like bash, is risky unless you are 100% certain about any shell metacharacters that might be present in the original string or the values of any variable expansions.

There is absolutely nothing risky about os.environ other than the exception that will be raised if the key (the env var name) is not present in the map. Which is why you should generally use os.getenv() since that makes it easier to handle the case where the env var isn't present.

Related