How to set environment variables in Python?
it complains saying that 1 has to be a string. I also want to know how to read the environment variables in Python (in the latter part of the script) once I set it.
19 Answers 19
Environment variables must be strings, so use
import os os.environ["DEBUSSY"] = "1"
to set the variable DEBUSSY to the string 1 .
To access this variable later, simply use
Child processes automatically inherit the environment of the parent process — no special action on your part is required.
On some platforms, modifying os.environ will not actually modify the system environment either for the current process or child processes. See the docs for more info: docs.python.org/2/library/os.html#os.environ
@Evan There might be some historical variants of Unix that don’t support putenv() , but for those Unixen there is nothing you can do anyway. Even old version of AIX and HPUX I worked with did support it. If anyone is actually able to find a computer not supporting it today, I have severe doubts they will be able to run Python on that computer. 🙂
Caution: to quote from @Evan’s reference above, Such changes to the environment affect subprocesses started with os.system(), popen() or fork() and execv(). In other words, keep in mind that this approach won’t modify the way your program is running, only the way your program’s children run. True, your program can set and read back environment variables, but only from the environment it configures for its children. See also: change current process environment. So far I haven’t found a way for a Python script to modify its parent env.
@SvenMarnach is the statement «child process automatically inherit the environment of the parent process’ true for shell like bash.
You may need to consider some further aspects for code robustness;
when you’re storing an integer-valued variable as an environment variable, try
os.environ['DEBUSSY'] = str(myintvariable)
then for retrieval, consider that to avoid errors, you should try
os.environ.get('DEBUSSY', 'Not Set')
possibly substitute ‘-1’ for ‘Not Set’
so, to put that all together
myintvariable = 1 os.environ['DEBUSSY'] = str(myintvariable) strauss = int(os.environ.get('STRAUSS', '-1')) # NB KeyError strauss = os.environ['STRAUSS'] debussy = int(os.environ.get('DEBUSSY', '-1')) print "%s %u, %s %u" % ('Strauss', strauss, 'Debussy', debussy)
It rarely makes sense to store -1 for a missing integer. A better bet would be myvar = int(os.environ.get(‘MYVAR’)) if os.environ.get(‘MYVAR’, ») != » else None – that way it would be None if no number was provided
If you are dealing with integers, a -1 makes sense. Though I would likely set a variable/constant to the value I would use for not set (e.g., value_not_set = ‘-1’ ). Then, you could use debussy = int(os.environ.get(‘DEBUSSY’, value_not_set))
os.environ behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get and set operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings.
For python 3, dictionaries use the in keyword instead of has_key
>>> import os >>> 'HOME' in os.environ # Check an existing env. variable True .
>>> import os >>> os.environ.has_key('HOME') # Check an existing env. variable True >>> os.environ.has_key('FOO') # Check for a non existing variable False >>> os.environ['FOO'] = '1' # Set a new env. variable (String value) >>> os.environ.has_key('FOO') True >>> os.environ.get('FOO') # Retrieve the value '1'
There is one important thing to note about using os.environ :
Although child processes inherit the environment from the parent process, I had run into an issue recently and figured out, if you have other scripts updating the environment while your python script is running, calling os.environ again will not reflect the latest values.
This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.
os.environ.data which stores all the environment variables, is a dict object, which contains all the environment values:
>>> type(os.environ.data) # changed to _data since v3.2 (refer comment below)
How to Add Python Path to Environment Variables on Windows 11
If you are getting errors when you run the python program, this could be due to the Python path not being set up on the environment variable on Windows 11. Here is how you can do it.
When you have installed Python on your Windows operating system, you have not selected the option to add the python path to the environment variable. That’s why you are getting an error. Python path is an environment variable that locates the installation location of python on your system.
How to Add Python Path to Environment Variables on Windows 11
If you fail to add Python to the PATH on your Windows OS, you can’t run the Python interpreter, start a virtual programming environment, or run commands like pip on the terminal.
When you run any python programming, the machine will look for an executable file on the Windows system variable. If the Python Path is not added, you will get an error that says – “python is not recognized as an internal or external command.“
Here is how you can fix it by adding Python Path to environment variables on Windows 11. For that, follow the following steps:
Step 1: Copy the installation location of Python. If you don’t know the installation location, click on the search option and search for python.exe. Right-click on it and select the “open file location” option.
Step 2: It will open the file explore window. Here, just copy the installation of python. Then continue with the next steps below.
Step 3: Open the “Settings” and click on the “System” tab from the left panel. Then, look for an option called “About” and click on that option present to the right of your screen.
Step 4: Now, you will get all your device specifications. Click on the “Advanced system settings” option; to access the “System Properties.”
Step 5: It will open the system properties window. Here click on the “Advanced” tab and select “Environment Variables” to open the environment variables windows.
Step 6: Here you will get two variables option. One is for user variables and another one is for system variables. Here under the system variable section, select the “Path” variable and click on the “Edit” button.
Step 7: Now click on “New” and add the python installation location. After that, click on “OK” to save the changes.
Step 8: Now to verify, open the command prompt and type python, then hit the [Enter] key. If the command returns the currently installed version of Python, it means; you’ve successfully added the python path to the environment variables.
Conclusion
That’s it; this is how you can add python to environment variables on Windows 11. You can also check our detailed guide on; how to setup Atom editor for Python on Windows 11.
I hope this article was helpful to you. If you liked the article, share it with your friends and family. If you have some suggestions, do not hesitate to leave them in the comments section below.