Python - temporarily modify the current process's environment

前端 未结 6 1821
清歌不尽
清歌不尽 2020-11-30 05:47

I use the following code to temporarily modify environment variables.

@contextmanager
def _setenv(**mapping):
    \"\"\"``with`` context to temporarily modi         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 06:08

    I was looking to do the same thing but for unit testing, here is how I have done it using the unittest.mock.patch function:

    def test_function_with_different_env_variable():
        with mock.patch.dict('os.environ', {'hello': 'world'}, clear=True):
            self.assertEqual(os.environ.get('hello'), 'world')
            self.assertEqual(len(os.environ), 1)
    

    Basically using unittest.mock.patch.dict with clear=True, we are making os.environ as a dictionary containing solely {'hello': 'world'}.

    • Removing the clear=True will let the original os.environ and add/replace the specified key/value pair inside {'hello': 'world'}.

    • Removing {'hello': 'world'} will just create an empty dictionary, os.envrion will thus be empty within the with.

提交回复
热议问题