0

I have a file, settings.py that looks like this:

import sys
import socket
import os
comp_name = socket.gethostname()

if comp_name == 'mymachine.local': 
    DB_VAR=os.environ.get('ENV_VAR') 
else: 
    print 'update settings.py with global variable names for this machine'
    sys.exit(1)

ENV_VAR is an environmental variable from the OS (I'm on OSX). I've confirmed that manually calling os.environ.get('ENV_VAR') from within the shell gives me the desired output.

The file execution.py lives in the same directory as settings.py and has the statement import settings in the header. print settings.comp_name returns the value 'mymachine.local', but print settings.DB_VAR returns the error:

AttributeError: 'module' object has no attribute 'DB_VAR'

Basically, I need to control which values are passed to these variables depending on the environment that the code is being run. Any pointers on what I'm doing wrong here would be very much appreciated.

aaron
  • 6,339
  • 12
  • 54
  • 80
  • Use `local_settings.py`? http://stackoverflow.com/questions/4909958/django-local-settings Your specific error seems to be occurring because DB_VAR is only defined inside the if block. – Bahrom Mar 23 '16 at 18:27
  • Difficult to debug this as it may be related to idiosyncracies of your machine. Can you put some `print` in there to verify what you say about the `comp_name`, and show the output of running the file? – BrenBarn Mar 23 '16 at 18:32
  • @BrenBarn: Putting print statements in the settings file doesn't result in any output in terminal when I call `import settings` inside the execution file. @BAH: same problem when I move the `DB_VAR` definition outside of the logic block--it just isn't inheriting a value, even when I can verify that variable is definitely defined on the OS with `echo ${DB_VAR}`. Any other thoughts? Even when I type `from settings import *` I still have the problem – aaron Mar 25 '16 at 19:05
  • @Aaron: If you put print statements and nothing is printed, it suggests the file isn't being imported. Are you running this as part of a framework of some kind, or are you just running `execution.py` directly from the command line? – BrenBarn Mar 25 '16 at 19:24
  • @BrenBran: OK, I have no idea why this should be, but changing the imported file's name from `settings.py` to `params.py` fixes the problem. Print statements work and global variables are dropped into the shell. Why might that be? – aaron Mar 25 '16 at 20:42
  • 1
    @Aaron: Probably because you had another file somewhere called `settings.py`, and that was getting imported instead. In your file where you do `import settings`, try printing `settings.__file__` to see where it's importing it from. – BrenBarn Mar 25 '16 at 20:52
  • that was it, thanks @BrenBarn--it was picking up `settings.pyc` – aaron Mar 25 '16 at 21:04

0 Answers0