With the os
module in Python we can easily access environment variables through the dict os.environ
. However, I found out that os.environ
does not just hold variables, but also globally defined shell functions (e.g. from the module
software package).
Is it possible from within Python to find out whether a given entry in os.environ
actually is a function and not a variable? Please note that a shell-agnostic solution is preferred, but I could settle for a Bash-specific solution as well.
# Checking if an Environment Variable Exists in Python import os if 'USER' in os. environ: print('Environment variable exists! ') else: print('Environment variable does not exist. ') # Returns: # Environment variable exists!
Using os. You can use os. environ to get a complete list of all the environment variables along with their values. To access an environment variable, you can use the [] syntax. For example, environ['HOME'] gives the pathname of your home directory in the Linux environment.
In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable you set earlier. For example, to check if MARI_CACHE is set, enter echo %MARI_CACHE%. If the variable is set, its value is displayed in the command window.
The os. getenv() method is used to extract the value of the environment variable key if it exists. Otherwise, the default value will be returned. Note: The os module in Python provides an interface to interact with the operating system.
This feature is bash-specific, so a test for an exported shell function needs to do what Bash does. Experimentation and source code show that Bash recognizes an environment variable as a shell function at startup by the presence of a () {
prefix in its value — if the prefix is missing, or even slightly altered, the variable is treated as an ordinary data variable.
Therefore, the equivalent Python check would look like this:
def is_env_shell_func(name):
return os.environ[name].startswith('() {')
One solution that I find to work (but that is ridiculously clumsy) is the following:
import subprocess
var = 'my_variable_name_i_want_to_check'
p = subprocess.Popen('declare -f ' + var, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
if p.returncode == 0:
print('function')
else:
print('variable')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With