Accessing python ConfigParser option values

My ini file has two sections. I'm trying to access the options from the first (Main) section (see file excerpt and test script below). I can only do so if I access the values from the main body of the python script I'm using (to print those values to a web page). If I put the code inside a function that returns the values, I get 'NameError': name '[option name]' not defined. Why? Either way, it seems like a lot of code just to access those values. Guidance appreciated!
import os
import sys
import ConfigParser

# Part I. This works:
parser = ConfigParser.SafeConfigParser()
parser.read('graphs.ini')

for section in parser.sections():
    if section == 'Main':
        for option in parser.options(section):
            value = parser.get(section, option)
            if option == 'base_dir':
                base_dir = value
            elif option == 'www_base':
                www_base = value
            elif option == 'contact_address':
                contact_address = value
            elif option == 'template_file':
                template_file = value

print 'first run:', base_dir, template_file

# Part II. This fails:
def parseConfig():

    parser = ConfigParser.SafeConfigParser()
    parser.read('graphs.ini')

    for section in parser.sections():
        if section == 'Main':
            for option in parser.options(section):
                value = parser.get(section, option)
                if option == 'base_dir':
                    base_dir = value
                elif option == 'www_base':
                    www_base = value
                elif option == 'contact_address':
                    contact_address = value
                elif option == 'template_file':
                    template_file = value

    #print base_dir, template_file
    return base_dir, www_base, contact_address, template_file

parseConfig()
print 'second run:', base_dir, template_file

Open in new window

# Excerpt from ini file
[Main]
base_dir = /path to base dir/
www_base = /path to url/
template_file = /path to template.html
contact_address = me@my-url.com

[Graphs]
omitted

Open in new window

sara_bellumAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

HonorGodSoftware EngineerCommented:
Because the variables are local to the routine (parseConfig).

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
HonorGodSoftware EngineerCommented:
Check out "scope" in the documentation (e.g., section 4.1 Naming and binding)
ilalopoulosCommented:
It seems like a lot of work because you run around in circles ;) To access the value of an option OPT from section SECT all you have to do after reading the ini file in your parser is to use parser.get('SECT', 'OPT')
See the attached code.

Cheers,

John
import os
import sys
import ConfigParser

# Part I. This works:
parser = ConfigParser.SafeConfigParser()
parser.read('graphs.ini')

print 'the same as first run but in one line:', parser.get('Main', 'base_dir'), parser.get('Main', 'template_file')

Open in new window

Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

sara_bellumAuthor Commented:
Gosh that's right John!! I got so turned around when I missed the fact that I had left in the single quotes after the equal sign (from an older config file that wasn't using the ConfigParser) that I tried something unnecessary while debugging this.

H-G, I'm still struggling with how to differentiate between variables that are local to a routine and variables that can be returned by a function, but that will take time I think.

Ordinarily I should just say thank you and close this out, but thought I'd push my luck:
the ini file excerpt I posted earlier omits the other section(s) - I post another excerpt below that I'm using to read values into a dict. The reason for this (and the weird format of this section of the ini file) is that I haven't figured out how to assign a proper sequence to the options as they are printed. I can't change the keys and I don't know how to sort parser options by value. Python docs for the version I use at work (2.5) can be hard to come by!

The code I post below is admittedly a hack  - I'm sure there's a better way to do this and I'm open to suggestions - if I need to open a new question let me know...

# ini file excerpt
[Stations]
MultiStation = 00-MultiStation
Met_Station = 02-Met Station
Coastal_Station = 03-Coastal Network
Indoor_Monitoring = 04-Temperature Gages
Soil_Monitoring = 05-Soil Moisture 

# the script
station_names = {}

for station in parser.options('Stations'):
    rhs = parser.get('Stations', station)

    if station not in station_names:
        station_names[station] = {}

    station_names[station] = rhs

map_list = sorted(station_names.iteritems(), key=lambda (k,v):(v,k))

for item in map_list:
    # optional variable names in case I need them
    station_name = item[0]
    station_descriptor = item[1]
    # numbers printed in test script to verify station order
    print item[1][0:3], item[1][3:]

Open in new window

HonorGodSoftware EngineerCommented:
> I'm still struggling with how to differentiate between variables that are local to a routine and variables that can be returned by a function, but that will take time I think.

  Well, if you have a variable that is local to a routine, then its value could be returned:

Executing the following script results in:
--------------------------------------------------
C:\>python bob.py
"x" is not a local variable
"y" is a local variable

C:\>
x = 0;                  # Global variable

def routine() :
  y = 'Something';      # Local variable

  if 'x' in locals() :  #
    print '"x" is a local variable';
  else :
    print '"x" is not a local variable';

  if 'y' in locals() :
    print '"y" is a local variable';
  else :
    print '"y" is not a local variable';

routine();

Open in new window

sara_bellumAuthor Commented:
I found a way to answer my other question:
for y in range(0, 16):   #number of options
    for lhss in parser.options('Stations'):
      rhss = parser.get('Stations', lhss)
      x = int(rhss[0:2])
      if x == y:
        station_list.append(rhss)
But for other reasons I still need a dict in most cases. Anyway, thanks very much!
HonorGodSoftware EngineerCommented:
Thank you for the grade & points.

Good luck & have a great day.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Scripting Languages

From novice to tech pro — start learning today.