4

I have a service where users upload egg files. The problem is that a settings.py file needs to be extracted by me and I should only accept some of the values in that file. The file consists of regular Python variables like:

VAR1 = 'Hello'
VAR2 = ['my.list']
VAR3 = {
    'a': 'b'
}

I need to extract these variables in a good manner and I have looked for a way to 'source' (Bash term I suppose..) the settings.py file to my worker Python file to extract the variables. I haven't found a way to do that when searching. Any ideas?

My (specific) solution

# Append path to sys.path
sys.path.insert(0, os.path.dirname('/path/to/settings.py'))

import settings as egg_settings
LOGGER.info('Settings: VAR1 = %s', egg_settings.VAR1)

# Remove from sys.path
sys.path.pop(0)
Sebastian Dahlgren
  • 957
  • 2
  • 11
  • 20
  • Do you have some criteria for which variables you'd like to accept, and which to ignore? – jgritty Jan 19 '13 at 05:44
  • Duplicate : http://stackoverflow.com/questions/714881/how-to-include-external-python-code-to-use-in-other-files – Suku Jan 19 '13 at 05:56

1 Answers1

8

If you just do import settings all the variables will be available like settings.VAR1 settings.VAR2 etc.

jgritty
  • 11,660
  • 3
  • 38
  • 60
  • 1
    Thanks, this was obvious but I needed to hear it obviously :). I updated my question with a more detailed solution that worked fine for me. The springing point being that I needed to add a part of the egg to the `sys.path` and then remove it again. – Sebastian Dahlgren Jan 19 '13 at 10:00