How to set and retrieve environment variable in Python

17,722

Solution 1

Try this one.

os.environ["CPATH"] = "/Users/cat/doc"

Python documentation is quite clear about it.

Calling putenv() directly does not change os.environ, so it’s better to modify os.environ.

Based on the documentation, the os.getenv() is available on most flavors of Unix and Windows. OS X is not listed.

Use rather the snippet below to retrieve the value.

value = os.environ.get('CPATH')

Solution 2

Use os.environ:

os.environ['CPATH'] = '/Users/cat/doc'    
print os.environ['CPATH']     # /Users/cat/doc
print os.environ.get('CPATH') # /Users/cat/doc

See the above link for more details:

If the platform supports the putenv() function, this mapping may be used to modify the environment as well as query the environment. putenv() will be called automatically when the mapping is modified.

Note Calling putenv() directly does not change os.environ, so it’s better to modify os.environ.

Share:
17,722
CatarinaCM
Author by

CatarinaCM

Updated on June 09, 2022

Comments

  • CatarinaCM
    CatarinaCM almost 2 years

    I need to set a environment variables in the python, and I try the commands bellow

    import os
    basepath = os.putenv('CPATH','/Users/cat/doc') 
    basepath = os.getenv('CPATH','/Users/cat/doc') 
    

    And when I print the varible, they are not set: print basepath None

    What i'm doing wrong?

    Rephrasing the question, I would like to create a base path based on a evironment variable. I'm testing this:

    os.environ["CPATH"] = "/Users/cat/doc"
    print os.environ["CPATH"]
    base_path=os.getenv('C_PATH')
    

    And when I try to print the basepath: print basepath it always return None