Python - temporarily modify the current process's environment

前端 未结 6 1820
清歌不尽
清歌不尽 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:09

    Using the gist here, you can save/restore local, global scope variable and environment variables: https://gist.github.com/earonesty/ac0617a5672ae1a41be1eaf316dd63e4

    import os
    from varlib import vartemp, envtemp
    
    x = 3
    y = 4
    
    with vartemp({'x':93,'y':94}):
       print(x)
       print(y)
    print(x)
    print(y)
    
    with envtemp({'foo':'bar'}):
        print(os.getenv('foo'))
    
    print(os.getenv('foo'))
    

    This outputs:

    93
    94
    3
    4
    bar
    None
    

提交回复
热议问题