What is the correct way to unset a linux environment variable in python?

PythonEnvironment Variables

Python Problem Overview


From the documentation:

> If the platform supports the unsetenv() function, you can delete items in this mapping to unset environment variables. unsetenv() will be called automatically when an item is deleted from os.environ, and when one of the pop() or clear() methods is called.

However I want something that will work regardless of the availability of unsetenv(). How do I delete items from the mapping if it's not available? os.environ['MYVAR'] = None?

Python Solutions


Solution 1 - Python

Just

del os.environ['MYVAR']

should work.

Solution 2 - Python

For those who search for an elegant way to unset environment variable without errors if the variable does not exist:

os.environ.pop('MYVAR', None)

That works exactly as:

if 'MYVAR' in os.environ:
    del os.environ['MYVAR']

But if you need to deal with the exception, do what other users suggested: del os.environ['MYVAR'] or os.environ.pop('MYVAR').

Solution 3 - Python

You can still delete items from the mapping, but it will not really delete the variable from the environment if unsetenv() is not available.

del os.environ['MYVAR']

Solution 4 - Python

Try this if you need a valid method, such as in TestCase.addCleanup()

os.environ.pop('MYVAR')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfredleyView Question on Stackoverflow
Solution 1 - PythonVinay SajipView Answer on Stackoverflow
Solution 2 - PythonFomalhautView Answer on Stackoverflow
Solution 3 - PythonSjoerdView Answer on Stackoverflow
Solution 4 - PythonQuanlongView Answer on Stackoverflow