- Python get current environment
- Environment Variables in Python – Read, Print, Set
- Environment Variables in Python
- How to Read Environment Variables in Python
- Printing all the Environment Variables in Python
- Getting Specific Environment Variable Value
- How to Check if an Environment Variable Exists?
- How to Set Environment Variable in Python
- Conclusion
- References:
Python get current environment
- Python | os.ctermid() method
- Python | os.environ object
- Python os.chdir() method
- Python | os.fchdir() method
- Python | os.getcwd() method
- Python | os.getenv() method
- Python | os.get_exec_path() method
- Python | os.geteuid() and seteuid() method
- Python | os.getgrouplist() method
- Python | os.getgroups() method
- Python | os.getlogin() method
- Python | os.getpgid() method
- Python | os.getpgrp() method
- Python | os.getpid() method
- Python | os.getppid() method
- Python | os.getresuid() and os.setresuid() method
- Python | os.getuid() and os.setuid() method
- Python | os.setregid() method
- Python | os.setreuid() method
- Python | os.setgroups() method
- Python | os.getsid() method
- Python | os.strerror() method
- Python | os.supports_bytes_environ object
- Python | os.umask() method
- Python | os.link() method
- Python | os.listdir() method
- Python | os.mkdir() method
- Python | os.makedirs() method
- Python | os.mkfifo() method
- Python | os.major() method
- Python | os.minor() method
- Python | os.makedev() method
- Python | os.readlink() method
- Python | os.remove() method
- Python | os.removedirs() method
- Python | os.rename() method
- Python | os.renames() method
- Python – os.replace() method
- Python | os.rmdir() method
- Python | os.scandir() method
- Python | os.stat() method
- Python | os.statvfs() method
- Python | os.sync() method
- Python | os.truncate() method
- Python | os.unlink() method
- os.walk() in Python
- Python | os.getenv() method
- Python | os.abort() method
- Python | os._exit() method
- Python | os.fork() method
- Python | os.kill() method
- Python | os.nice() method
- Python | os.system() method
- Python | os.times() method
- Python | os.wait() method
- Python | os.getenv() method
- Python | os.open() method
- Python | os.get_blocking() method
- Python | os.isatty() method
- Python | os.openpty() method
- Python | os.pipe() method
- Python | os.pipe2() method
- Python | os.pread() method
- Python | os.write() method
- Python | os.pwrite() method
- Python | os.read() method
- Python | os.sendfile() method
- Python | os.set_blocking() method
- Python | os.ctermid() method
- Python | os.environ object
- Python os.chdir() method
- Python | os.fchdir() method
- Python | os.getcwd() method
- Python | os.getenv() method
- Python | os.get_exec_path() method
- Python | os.geteuid() and seteuid() method
- Python | os.getgrouplist() method
- Python | os.getgroups() method
- Python | os.getlogin() method
- Python | os.getpgid() method
- Python | os.getpgrp() method
- Python | os.getpid() method
- Python | os.getppid() method
- Python | os.getresuid() and os.setresuid() method
- Python | os.getuid() and os.setuid() method
- Python | os.setregid() method
- Python | os.setreuid() method
- Python | os.setgroups() method
- Python | os.getsid() method
- Python | os.strerror() method
- Python | os.supports_bytes_environ object
- Python | os.umask() method
- Python | os.link() method
- Python | os.listdir() method
- Python | os.mkdir() method
- Python | os.makedirs() method
- Python | os.mkfifo() method
- Python | os.major() method
- Python | os.minor() method
- Python | os.makedev() method
- Python | os.readlink() method
- Python | os.remove() method
- Python | os.removedirs() method
- Python | os.rename() method
- Python | os.renames() method
- Python – os.replace() method
- Python | os.rmdir() method
- Python | os.scandir() method
- Python | os.stat() method
- Python | os.statvfs() method
- Python | os.sync() method
- Python | os.truncate() method
- Python | os.unlink() method
- os.walk() in Python
- Python | os.getenv() method
- Python | os.abort() method
- Python | os._exit() method
- Python | os.fork() method
- Python | os.kill() method
- Python | os.nice() method
- Python | os.system() method
- Python | os.times() method
- Python | os.wait() method
- Python | os.getenv() method
- Python | os.open() method
- Python | os.get_blocking() method
- Python | os.isatty() method
- Python | os.openpty() method
- Python | os.pipe() method
- Python | os.pipe2() method
- Python | os.pread() method
- Python | os.write() method
- Python | os.pwrite() method
- Python | os.read() method
- Python | os.sendfile() method
- Python | os.set_blocking() method
Environment Variables in Python – Read, Print, Set
Environment variables is the set of key-value pairs for the current user environment. They are generally set by the operating system and the current user-specific configurations. For example, in a Unix environment, the environment variables are set using the user profile i.e. .bash_profile, .bashrc, or .profile files.
Environment Variables in Python
You can think of environment variables as a dictionary, where the key is the environment variable name and the value is the environment variable value.
How to Read Environment Variables in Python
We can use Python os module “environ” property to get the dictionary of all the environment variables. When the os module is loaded by Python interpreter, the environ value is set. Any further changes in the environment variables through external programs will not get reflected in the already running Python program.
Printing all the Environment Variables in Python
The os.environ variable is a dictionary-like object. If we print it, all the environment variables name and values will get printed.
import os # printing environment variables print(os.environ)
If you want to print the environment variables in a better readable way, you can print them in a for loop.
import os for k, v in os.environ.items(): print(f'=')
PATH=/Users/pankaj/Documents/PyCharmProjects/PythonTutorialPro/venv/bin:/Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home/bin:/Library/PostgreSQL/10/bin:/Users/pankaj/Downloads/mongodb/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Users/pankaj/Downloads/apache-maven-3.5.3/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin PS1=(venv) MAVEN_OPTS=-Xmx2048m -XX:MaxPermSize=128m VERSIONER_PYTHON_VERSION=2.7 LOGNAME=pankaj XPC_SERVICE_NAME=com.jetbrains.pycharm.40096 PWD=/Users/pankaj/Documents/PycharmProjects/AskPython/hello-world PYCHARM_HOSTED=1 PYTHONPATH=/Users/pankaj/Documents/PycharmProjects/AskPython SHELL=/bin/zsh PAGER=less LSCOLORS=Gxfxcxdxbxegedabagacad PYTHONIOENCODING=UTF-8 OLDPWD=/Applications/PyCharm CE.app/Contents/bin VERSIONER_PYTHON_PREFER_32_BIT=no USER=pankaj ZSH=/Users/pankaj/.oh-my-zsh TMPDIR=/var/folders/1t/sx2jbcl534z88byy78_36ykr0000gn/T/ SSH_AUTH_SOCK=/private/tmp/com.apple.launchd.jkodHSyv2v/Listeners VIRTUAL_ENV=/Users/pankaj/Documents/PyCharmProjects/PythonTutorialPro/venv XPC_FLAGS=0x0 PYTHONUNBUFFERED=1 M2_HOME=/Users/pankaj/Downloads/apache-maven-3.5.3 __CF_USER_TEXT_ENCODING=0x1F5:0x0:0x0 Apple_PubSub_Socket_Render=/private/tmp/com.apple.launchd.wL2naXrbuW/Render LESS=-R LC_CTYPE=UTF-8
Getting Specific Environment Variable Value
Since os.environ is a dictionary object, we can get the specific environment variable value using the key.
import os home_dir =os.environ['HOME'] username = os.environ['USER'] print(f' home directory is ')
Output: pankaj home directory is /Users/pankaj
However, this way to get the environment variable will raise KeyError if the environment variable is not present.
>>> import os >>> env_var = input('Please enter the environment variable name:\n') Please enter the environment variable name: data >>> print(os.environ[env_var]) Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 678, in __getitem__ raise KeyError(key) from None KeyError: 'data' >>>
A better way to get the environment variable is to use the dictionary get() function. We can also specify the default value if the environment variable is not present.
>>> import os >>> env_var = input('Please enter the environment variable name:\n') Please enter the environment variable name: data >>> print(os.environ.get(env_var)) None >>> print(os.environ.get(env_var, 'CSV')) CSV
How to Check if an Environment Variable Exists?
We can use the “in” operator to check if an environment variable exists or not.
import os env_var = input('Please enter the environment variable name:\n') if env_var in os.environ: print(f' value is ') else: print(f' does not exist')
# Run 1 Please enter the environment variable name: datatype datatype does not exist # Run 2 Please enter the environment variable name: USER USER value is pankaj
How to Set Environment Variable in Python
We can set the environment variable value using the syntax: os.environ[env_var] = env_var_value
import os env_var = input('Please enter environment variable name:\n') env_var_value = input('Please enter environment variable value:\n') os.environ[env_var] = env_var_value print(f'= environment variable has been set.')
Please enter environment variable name: datatype Please enter environment variable value: CSV datatype=CSV environment variable has been set.
If the environment variable already exists, it will be overwritten by the new value. The environment variable will be set only for the current session of the Python interpreter. If you want to change to be permanent, then you will have to edit the user profile file in the Python program.
Conclusion
It’s very easy to work with environment variables in Python. We can read, add, and update environment variables for the current execution.