6

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

pgiecek
  • 7,970
  • 4
  • 39
  • 47
CatarinaCM
  • 1,145
  • 3
  • 13
  • 21

3 Answers3

12

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')
pgiecek
  • 7,970
  • 4
  • 39
  • 47
  • In this way I can print the env variable but when I try to ascribe it to a base path, eg: base_path = os.getenv('CPATH') – CatarinaCM Oct 01 '14 at 16:42
  • @CatarinaCM, pardon? Modifying `os.environ` quite certainly does update the environment variables active for your script -- and `base_path = os.environ.get('CPATH')` [if you want `None` in the not-found case] is the best-practices approach to retrieval. If you're seeing contrary results, please provide a reproducer so we know how you're testing. – Charles Duffy Oct 01 '14 at 16:44
  • Use `os.environ.get('CPATH')` as @Charles suggested. – pgiecek Oct 01 '14 at 16:52
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.

Ofiris
  • 6,047
  • 6
  • 35
  • 58
0

It's a good practice to restore the environment variables at function completion. You may need something like the modified_environ context manager describe in this question to restore the environment variables.

Usage example:

with modified_environ(CPATH='/Users/cat/doc'):
    call_my_function()
Community
  • 1
  • 1
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103