How to use bash Environment Variables in Python - part 3

Setting and clearing environment variables

You can change the value of an existing environment variable, in your current session:

os.environ['HOME'] = '/path/to/new/home'

And you can create your own environment variable, for your current session.

You might want to be careful, because if the environment variable already exists, it will be overwritten by the new value.

os.environ['NEW_ENV_VAR'] = 'desired_value'

You can clear a single environment variable in your current session using os.environ.pop() with the name of your environment variable as key.

If you want to clear all environment variables from your current session, you can use os.environ.clear().

os.environ.pop('PWD')
os.environ.clear()

Conclusion

It is relatively easy to work with bash environment variables in your Python scripts.

You can read, update or add environment variables for your current session, using the os.environ package.


Other articles:

How to use bash Environment Variables in Python - part 1

How to use bash Environment Variables in Python - part 2

Linux Bash shell variables

Linux Bash shell variables - Local Variables

Linux Bash shell variables - Environment Variables

How to create Linux Bash shell variables

How to remove Linux Bash shell variables