[Tutor] I Give Up. - Follow up post

Brian Gustin brian at daviesinc.com
Tue Jul 4 19:56:43 CEST 2006


OK see, what I was doing originally (and I found time to finally get it 
partially working)

I have a configuration file that may be edited by webmaster thus

[Ports]

http = 80
https = 443
http1 = 81
smtp = 25
smtp2 = 587

(the above is a small example, it could be *anything* )

Now I have a function that takes machine, protocol, and a dictionary of 
last alerts (would be empty if none)

The whole is a small multiple machine monitoring script, By the way...

The configuration file needed to be read by config parser and assign the 
config name as if it were a variable, and the value along with it

I tried it by opening a file , but could find no way to do variable 
variables

(In PHP, you can do something to the effect of:
name = value
name1 = value1

and then read it in as a file , which builds an array (AKA dictionary)
and then just assign thus:

foreach ($filearray as $key => $value)
{
	$$key = $value
}

in python I could see no way to do so, so I ended up with configparser, 
which I *finally* got working - working code below
I am still working on this , as I wanna do it in python (currently 
operational in Perl , and running as a daemon, which I want this code to 
do eventually)

So, the below is a working example of reading a config file in python 
using configparser

Also note: I found that ConfigParser != configparser (it is case sensitive)

Just wanted to post this back in case anyone else needs to figure out 
how to use configparser in python.

import ConfigParser
cfg = ConfigParser.SafeConfigParser()
     cfg.read("/home/brian/pymon.cfg")
     if cfg.has_section("Parameters"):
         myparams = cfg.items("Parameters")
         for item in myparams:
             parameter[item[0]] = item[1]
     else:
         log_error("Parameters","not found")
     if cfg.has_section("Ports"):
         ports = cfg.items("Ports")
         for port in ports:
             watch_port[port[0]] = port[1]
     else:
         log_error("Ports","Not Found")
     if cfg.has_section("Hosts"):
         hostnames = cfg.items("Hosts")
         for hostname in hostnames:
             watch_hosts[hostname[0]] = hostname[1]
     else:
         log_error("Hosts","Not Found")
     if cfg.has_section("IP Addresses"):
         ips = cfg.items("IP Addresses")
         for ip in ips:
             watch_ips[ip[0]] = ip[1]
     else:
         log_error("IP Addresses","Not Found")
     if cfg.has_section("Alerts"):
         alerts_to = cfg.items("Alerts")
     else:
         log_error("Hosts","Not Found")
     print parameter
     print watch_port
     print watch_hosts
     print watch_ips
     print alerts_to


More information about the Tutor mailing list