How to set environment variables in Python?

前端 未结 11 1766
情话喂你
情话喂你 2020-11-22 04:00

I need to set some environment variables in the Python script and I want all the other scripts that are called from Python to see the environment variables\' set.

If

11条回答
  •  一生所求
    2020-11-22 04:38

    os.environ behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get and set operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings.

    Python 3

    For python 3, dictionaries use the in keyword instead of has_key

    >>> import os
    >>> 'HOME' in os.environ  # Check an existing env. variable
    True
    ...
    

    Python 2

    >>> import os
    >>> os.environ.has_key('HOME')  # Check an existing env. variable
    True
    >>> os.environ.has_key('FOO')   # Check for a non existing variable
    False
    >>> os.environ['FOO'] = '1'     # Set a new env. variable (String value)
    >>> os.environ.has_key('FOO')
    True
    >>> os.environ.get('FOO')       # Retrieve the value
    '1'
    

    There is one important thing to note about using os.environ:

    Although child processes inherit the environment from the parent process, I had run into an issue recently and figured out, if you have other scripts updating the environment while your python script is running, calling os.environ again will not reflect the latest values.

    Excerpt from the docs:

    This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.

    os.environ.data which stores all the environment variables, is a dict object, which contains all the environment values:

    >>> type(os.environ.data)  # changed to _data since v3.2 (refer comment below)
    
    

提交回复
热议问题