We can run many programs from bash, including Python. To run the Python interpreter from the bash shell, just type python
at the command prompt.
Once inside the command prompt, you can access environment variables like this:
import os
print(os.environ["FOOD"])
The os
package is built into the Python standard library, and contains many useful functions for working with the operating system.
os.environ
is a dictionary containing all of the values of environment variables. You can access any environment variable by specifying it as a key, just like with any Python dictionary.
This shows you a hint of the power of environment variables -- we can use them to set configuration in Python scripts and in other places. This is useful when configuration is secret (like access keys), or is changing quickly.
Instructions
Type python
to fire up the Python interpreter.
-
In the interpreter, you can run Python commands by typing them in and hitting enter at the end of each line.
-
Run the following code in the interpreter:
import osprint(os.environ["FOOD"])
- When you're done, type
exit()
to exit the interpreter.
Finally, type echo $FOOD
to verify that the value of the FOOD
variable is the same in Python and in the shell.