Skip to content

Instantly share code, notes, and snippets.

@iiie
Created June 24, 2012 09:46
Show Gist options
  • Save iiie/2982655 to your computer and use it in GitHub Desktop.
Save iiie/2982655 to your computer and use it in GitHub Desktop.
Get env in virtualenv...
#!/usr/bin/env python
# Author: iiie
# Need: Get environment variables into virtualenv / Django
# Usage:
# Add one or more keys:
# notku config:add AWS_KEY=abc123 [ANOTHER_KEY=another_value=allowed ...]
# Removed one or more keys:
# notku config:remove AWS_KEY [ANOTHER_KEY ...]
# List all keys
# notku config
# List all keys for export (I'd use this for bash)
# notku export
# Run manage.py with the virtualenv, and env
# notku path/to/manage.py runserver
# notku path/to/manage.py shell
#
import ConfigParser
__all__ = ('NotKu', 'main')
class NotKu(object):
def __init__(self, virtualenv_config, section='env'):
self.ve_conf = virtualenv_config
self.conf = ConfigParser.SafeConfigParser()
try:
self.conf.read(self.ve_conf)
except IOError, e:
# Assuming that there isn't one yet.
print e
pass
self.section = section
if not self.conf.has_section(section):
self.conf.add_section(section)
def add_env(self, key, value):
self.conf.set(self.section, key, value)
def remove_env(self, key):
self.conf.remove_option(self.section, key)
def get_env(self, section=None):
if not section:
section = self.section
try:
return self.conf.items(section)
except ConfigParser.NoSectionError:
return []
def save(self):
with open(self.ve_conf, 'wb') as configfile:
self.conf.write(configfile)
def main():
import os
import sys
config = os.path.join(os.environ['VIRTUAL_ENV'], '.envs')
notku = NotKu(config)
cmd = sys.argv[1]
if cmd == 'config':
for key, value in notku.get_env():
print '{0} => {1}'.format(key, value)
return
if cmd == 'config:add':
print 'Adding config vars'
for pair in sys.argv[2:]:
splitpair = pair.split('=', 1)
print ' {0} => {1}'.format(*splitpair)
notku.add_env(*splitpair)
print splitpair
os.environ.update(dict([splitpair]))
elif cmd == 'config:remove':
for key in sys.argv[2:]:
notku.remove_env(key)
elif cmd == 'config:export':
env = map(lambda x: '{0}="{1}"'.format(*x), notku.get_env())
print ' '.join(env)
return
elif 'manage.py' in cmd:
env = map(lambda x: '{0}="{1}"'.format(*x), notku.get_env())
env.extend(['python', cmd])
env.extend(sys.argv[2:])
os.system(' '.join(env))
return
else:
print 'Unknown command {0}'.format(cmd)
return
notku.save()
if '__main__' == __name__:
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment