Understanding and being able to change environment variables can be really useful to quickly alter a program’s behavior. Usually, we can do this by just making some minor changes in the environment the programs are running in. From a command line prompt, we can check these variables using the env or nth command.
That’s a lot of different variables, but what are they for? It all depends on the variable itself. Some are more important than others. For example, the path variable is a very important one. Let’s print out the contents of just that one using the echo command.
Echo is a command that we use to print texts and Linux shell, and when we want to access the value of the variable in the shell, we need a prefix and name of the variable with a dollar sign. Here, we’ve printed the contents of the path variable. The shell uses this environment variable to figure out where to look for executable files, and we call them while specifying a directory. All those directories listed there are where the shell will look for programs. For example, when we call the Python 3 program, the shell checks each of the directories listed in the path variable in order, and when it finds a program called Python 3, it executes it.
We can read the contents of these variables from Python. Let’s use a Python script to check that out.
To access environment variables, we use the Environ dictionary provided by the OS module. In this case, we’re using a dictionary method that we haven’t used before. The getMethod is a bit similar to how we’ve been accessing dictionary values up until now. The difference is what happens when the value isn’t present. When we retrieve a value from a dictionary using the key as in OS.environ[fruit] and the key isn’t present, we get an error. If we use a getMethod instead, we can specify what value should be returned if the key isn’t present. In other words, the getMethod allows us to specify a default value when the key that we’re looking for isn’t in the dictionary. So what we’re asking Python to do is try to retrieve the value associated with the key, but if the key’s not defined return an empty string instead. We’re doing this for three different variables; home, shell, and fruit. Let’s run the script and see what happens.
We got the values for home and shell, but not for fruit. Well, that’s because that variable isn’t defined in the current environment. To define it in a way that our script we’ll be able to see it, we need to run this in our command-line.
So we define the variable by just setting a value using the equal sign and leaving no spaces in between. Along with this, the export keyword tells a shell that we want the value we set to be seen by any commands that we call. Now, let’s call our script again.
Cool, this time we got the value that we wanted. So you now know how to get the value of any environment variables from your Python scripts. Coming up, we’ll dive into how command lines tell us whether they’ve succeeded or failed.