Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set and retrieve environment variable in Python

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

like image 589
CatarinaCM Avatar asked Oct 01 '14 16:10

CatarinaCM


People also ask

How do I get an environment variable in Python?

getenv() method is used to extract the value of the environment variable key if it exists. Otherwise, the default value will be returned. Note: The os module in Python provides an interface to interact with the operating system.

How do I set environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.


2 Answers

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')
like image 197
pgiecek Avatar answered Sep 22 '22 17:09

pgiecek


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.

like image 35
Ofiris Avatar answered Sep 23 '22 17:09

Ofiris