Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Sourcing" a Python file from another

Tags:

python

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)
like image 942
Sebastian Dahlgren Avatar asked Feb 18 '23 19:02

Sebastian Dahlgren


1 Answers

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

like image 177
jgritty Avatar answered Feb 20 '23 12:02

jgritty